Adding a new column to each element in a list of tables or data frames

前端 未结 6 1648
没有蜡笔的小新
没有蜡笔的小新 2020-11-27 03:51

I have a list of files. I also have a list of \"names\" which I substr() from the actual filenames of these files. I would like to add a new column to each of t

6条回答
  •  一整个雨季
    2020-11-27 04:10

    The purrr way, using map2

    library(dplyr)
    library(purrr)
    
    map2(filelist, ID, ~cbind(.x, SampleID = .y))
    
    #[[1]]
    #  x y SampleId
    #1 1 a       1A
    #2 2 b       1A
    #3 3 c       1A
    
    #[[2]]
    #  x y SampleId
    #1 4 d       IB
    #2 5 e       IB
    #3 6 f       IB
    

    Or can also use

    map2(filelist, ID, ~.x %>% mutate(SampleId = .y))
    

    If you name the list, we can use imap and add the new column based on it's name.

    names(filelist) <- c("1A","IB")
    imap(filelist, ~cbind(.x, SampleID = .y))
    #OR
    #imap(filelist, ~.x %>% mutate(SampleId = .y))
    

    which is similar to using Map

    Map(cbind, filelist, SampleID = names(filelist))
    

提交回复
热议问题