简体   繁体   English

循环遍历三个数据帧列表 R

[英]Loop through three lists of dataframes R

I have three filetypes that I want to combine in R. I have worked out how to read in the filetypes so that for each I have three lists of dataframes:我想在 R 中组合三种文件类型。我已经研究出如何读取文件类型,以便为每个文件类型提供三个数据框列表:

anno_files<-list.files(path = ".", pattern = ".hg19_multianno.exonic.txt")
cancer_files<-list.files(path = ".", pattern = ".exonic.cancervar")
vcf_files<-list.files(path = ".", pattern = ".hg19.annovar.and.vcf")

myfilelist <- lapply(anno_files, read.delim)
myfilelist2<-lapply(cancer_files, read.delim)
myfilelist3<-lapply(vcf_files, read.delim)

I now want to loop through each list (so in the first instance take the first dataframe from each list) and do things like merge columns etc. Something like:我现在想遍历每个列表(因此在第一个实例中从每个列表中获取第一个数据框)并执行诸如合并列等操作。例如:

start of loop:
    all_annotation<-left_join(myfilelist[[1]], myfilelist2[[1]], by = c("V1",  "V2", "V3","V4","V5" ))
    all_annotation<-left_join(all_annotation, myfilelist3[[1]] by = c("V1",  "V2", "V3","V4","V5" ))
    names(all_annotation)<- c("blah","blah,"blah")
write.csv(all_annotation)
end of loop:

As you can tell I'm a newbie and so any suggestions for this answer or an alternative, more elegant way of doing this would be very appreciated.正如你所知道的,我是一个新手,因此对于这个答案或替代的、更优雅的方法的任何建议将不胜感激。

You can write a function to merge 3 files and write it as csv -您可以编写一个函数来合并 3 个文件并将其写为 csv -

merge_and_write <- function(x, y, z, i) {
  all_annotation <- x %>%
    left_join(y, by = c("V1", "V2", "V3","V4","V5")) %>%
    left_join(z, by = c("V1",  "V2", "V3","V4","V5"))
  names(all_annotation) <- c("blah","blah","blah")
  write.csv(all_annotation, paste0('file', i, '.csv'), row.names = FALSE)
}

Use Map to apply it to every instance in parallel from each list.使用Map将其并行应用于每个列表中的每个实例。

Map(merge_and_write, myfilelist, myfilelist2, myfilelist3, seq_along(myfilelist))

This should create files file1.csv , file2.csv etc in your working directory.这应该在您的工作目录中创建文件file1.csvfile2.csv等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM