Maral Dorri
Maral Dorri

Reputation: 478

Set a column in dataframes of a list equal to the name of the dataframe in the list in R

I have a list of dataframe such as:

my_list <- list(`1` = data.frame(x = c(1,2,3), y = c(3,3,3)),
                `2` = data.frame(x = c(4,8,1), y = c(4,4,4)),
                `3` = data.frame(x = c(5,7,6), y = c(8,8,8)))
print(my_list)

$`1`
  x y
1 1 3
2 2 3
3 3 3

$`2`
  x y
1 4 4
2 8 4
3 1 4

$`3`
  x y
1 5 8
2 7 8
3 6 8

I would like to write a function to set the y column in the dataframes in the list my_list to the corresponding names(my_list). The desired output would be

$`1`
  x y
1 1 1
2 2 1
3 3 1

$`2`
  x y
1 4 2
2 8 2
3 1 2

$`3`
  x y
1 5 3
2 7 3
3 6 3

Upvotes: 0

Views: 31

Answers (2)

Onyambu
Onyambu

Reputation: 79298

You could do:

library(tidyverse)
imap(my_list, ~mutate(.x, y = .y))

In base R, you could do:

Map(transform, my_list, y = names(my_list))
$`1`
  x y
1 1 1
2 2 1
3 3 1

$`2`
  x y
1 4 2
2 8 2
3 1 2

$`3`
  x y
1 5 3
2 7 3
3 6 3

Upvotes: 1

Jeremy
Jeremy

Reputation: 876

If you are familiar with for loops, just wrap a for loop within your function.

# build your function
# input your data list, loop through each of dataframe
# do what you need, then save the output

your_function <- function(data_list){
  for (i in 1:length(data_list)){
  data_list[[i]]$y <- names(data_list)[[i]]
  }
  return(data_list)
}

# now run your function
output <- your_function(my_list)

# check outputs
print(output)

Upvotes: 2

Related Questions