spread a data frame in a list in r

To spread a data frame within a list, you can use the lapply() function along with the tidyr package's spread() function. Here is an example code block:

main.r
library(tidyr)

# Sample data frame within a list
list_df <- list(df1 = data.frame(id = 1:3, 
                                  name = c("A", "B", "C"), 
                                  value = c(10, 20, 30)),
                df2 = data.frame(id = 1:3, 
                                  name = c("X", "Y", "Z"), 
                                  value = c(100, 200, 300)))

# Use lapply() to apply spread() to each data frame within the list
spread_list <- lapply(list_df, spread, key = name, value = value)

# Print the result
spread_list
544 chars
16 lines

In this example, we have a list called list_df comprised of two data frames with 3 rows and 3 columns each. We then use lapply() to apply spread() to each data frame within the list. The key argument specifies the column in each data frame used to create new columns, and the value argument specifies the column used to fill these new columns. The resulting list of spread data frames is stored in spread_list.

gistlibby LogSnag