Looping through list of data frames in R

前端 未结 3 858
忘掉有多难
忘掉有多难 2020-12-05 09:06

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         


        
相关标签:
3条回答
  • 2020-12-05 09:26

    Just use length(dfList)?

    for(i in 1:length(dfList))
    {
        a <- grep("One", names(dfList[[i]]))
        ... #etc.
    }
    

    Using lapply will be faster.

    ChangeNames = function(Data)
    {
        a = grep("One", names(Data))
        b = grep("Two", names(Data))
        names(Data)[c(a,b)] <- c("R1", "R2")
        return(Data)
    }
    lapply(dfList, ChangeNames) #Returns list of renamed data frames.
    
    0 讨论(0)
  • 2020-12-05 09:28
    > 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
    
    0 讨论(0)
  • 2020-12-05 09:49

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

    library(plyr)
    result_list <- llply(list_of_df, function(x) {
                    # do the replacing
                    return(x)
                    })
    
    0 讨论(0)
提交回复
热议问题