R name colnames and rownames in list of data.frames with lapply

后端 未结 2 1677
后悔当初
后悔当初 2020-12-16 07:51

I\'m pretty frustrated because I dont know how I achieve the naming of the columns and rows in a list of data.frames. I mean I want to avoid using a loop. So I figured I cou

相关标签:
2条回答
  • 2020-12-16 08:09

    I'll prefer setNames in this case

    set.seed(1)
    datalist <- list(dat1 = data.frame(A = 1:10, B = rnorm(10)),
                     dat2 = data.frame(C = 100:109, D = rnorm(10))
                     )
    lapply(datalist, names)
    ##  $dat1
    ## [1] "A" "B"
    
    ## $dat2
    ## [1] "C" "D"
    
    datalist <- lapply(datalist, setNames, paste0("col", 1:2))
    lapply(datalist, names)
    ## $dat1
    ## [1] "col1" "col2"
    
    ## $dat2
    ## [1] "col1" "col2"
    

    EDIT

    A more general solution to modify rownames and colnames within a list

    lapply(datalist, "colnames<-", paste0("col", 1:2))
    lapply(datalist, "rownames<-", letters[1:10])
    
    0 讨论(0)
  • 2020-12-16 08:27

    You need to remember that the object x inside the lapply is not the original object, but a copy. Changing the colnames of the copy does not impact the original object. You need to return x in order to get a new copy of the object that includes the new names.

    new_obj = lapply(a, function(x) {
       colnames(x) <- paste("col",1:10,sep="")
       return(x)
      })
    
    0 讨论(0)
提交回复
热议问题