r - 循环遍历三个数据帧列表 R
问题描述
我有三个要在 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)
我现在想遍历每个列表(因此首先从每个列表中获取第一个数据帧)并执行合并列等操作。例如:
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:
如您所知,我是新手,因此对于此答案或替代方法的任何建议,将不胜感激。
解决方案
您可以编写一个函数来合并 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)
}
用于Map
将它从每个列表并行应用于每个实例。
Map(merge_and_write, myfilelist, myfilelist2, myfilelist3, seq_along(myfilelist))
这应该在您的工作目录中创建文件file1.csv
等。file2.csv
推荐阅读
- javascript - 是否可以在无头 chrome 中列出/杀死/...所有待处理的承诺/异步事件?
- android - 从网页获取 CSS 并将其加载到 android webview
- reactjs - 如何使用本机反应校准相机?
- python - 在 Pypy venv 中找不到用于烧瓶 wsgi 的模块
- python - 编写多个 try 子句以将 json 字符串对象转换为数据类的更好方法是什么?
- python - 多维切片数组 Python
- amazon-s3 - 0/3 个节点可用:1 个节点具有 pod 无法容忍的污点,2 个 cpu 不足。MR3 蜂巢
- r - R 编程中的 mclapply - 如何确保使用所有内核和内存
- android - 添加Yandex地图(mapkit)时项目未建
- react-redux - Array.indexOf 不是函数