说我有一个列表lists
:
> lists
$a
[1] "fas" "asdfas" "adfaff" ...
$b
[1] "jnfg" "gfsdgs" "fdsafa" ...
...
我想将每个列表导出到自己的csv文件中,文件名是列表索引。我尝试使用lapply
代替for循环来实现,这可能吗?对我来说困难的是如何在FUN
内提取列表索引(或本例中的名称)?例如,如果我随机命名它,我可以这样做:
lapply(lists, function (x)
write.table(paste(sample(1:100000000,1), ".csv", sep=""),
sep=",", col.names=F, row.names=F))
修改:示例dput
:http://pastebin.com/a0eEkT1z
编辑2:更短的样本:(←这一个更明智)
list(c("Itm2a", "Rplp2", "Arl6ip5", "Crygn", "Znrf1", "Gm5766",
"D19Ertd652e", "Nkap"), c("Sergef", "2610002I17Rik", "Hjurp",
"Mns1", "Top3a", "Ldlrap1", "Ube2c", "Cnot3", "Irf6"), c("Fam109a",
"Rps3a", "Dut", "Atm", "Fancg", "S100a5", "Lpcat2", "Sec23ip"
))
答案 0 :(得分:3)
你做不到。一个技巧是使用lapply
循环遍历名称,或者您可以使用Map
执行类似
Map(function (name, data)
write.table(data, paste0(name, ".csv"),
sep=",", col.names=F, row.names=F)
, names(lists), lists)
答案 1 :(得分:2)
您可以使用mapply
mapply(function(name, x) {
write.table(x, paste0(name, ".csv"), sep=",", col.names=F, row.names=F)
}, names(lists), lists)
或者实际上也可以使用lapply
lapply(names(lists), function(name) {
write.table(lists[name], paste0(name, ".csv"), sep=",", col.names=F, row.names=F)
})