Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through list of data frames in R

Tags:

r

I have a series of data frames, df1 df2, where each data frame follow this structure:

x <- c(1:5)
y <- c(1:5)
df1 <- data.frame("Row One"=x, "Row Two"=y)

Sample output for df1:

 Row.One    Row.Two
    1           1
    2           2
    3           3
    4           4
    5           5

I put each data frame into a list dfList <- list(df1,df2...)

Now I want to loop through each data frame object in this list to replace the column names using this command:

a <- grep("One", colnames(df))
b <- grep("Two", colnames(df))

names(df)[a] <- "R1"
names(df)[b] <- "R2"

How can I structure a loop in R so that I no matter how many data frames are in the list object the column name changing commands above will be applied to each data frame?

like image 640
AME Avatar asked Oct 18 '13 22:10

AME


People also ask

How do I combine a list of data frames in R?

To combine data frames stored in a list in R, we can use full_join function of dplyr package inside Reduce function.

Can you include an R list as a column of a data frame?

Now to add a list as a column, create a list with required values. Then, use the name of the data frame and the new column separated by $ and assign this to the list so created. This will assign the list to the column name given and then add it to the dataframe.


2 Answers

> df1 <- data.frame("Row One"=x, "Row Two"=y)
> df2 <- data.frame("Row Two"=y,"Row One"=x)
> dfList <- list(df1,df2)
> lapply(dfList, function(x) {
                    names(x)[ grep("One", names(x))] <- "R1"
                    names(x)[ grep("Two", names(x))] <- "R2"
                    x} )
[[1]]
  R1 R2
1  1  1
2  2  2
3  3  3
4  4  4
5  5  5

[[2]]
  R2 R1
1  1  1
2  2  2
3  3  3
4  4  4
5  5  5
like image 101
IRTFM Avatar answered Oct 14 '22 16:10

IRTFM


Or use llply (from plyr) or lapply like so:

library(plyr)
result_list <- llply(list_of_df, function(x) {
                # do the replacing
                return(x)
                })
like image 35
Maiasaura Avatar answered Oct 14 '22 16:10

Maiasaura