如何在lapply的FUN中提取列表项的索引或名称? [英] How do I extract the index or name of the list item within FUN of lapply?
问题描述
说我有一个列表列表列表
:
> lists
$a
[1] "fas" "asdfas" "adfaff" ...
$b
[1] "jnfg" "gfsdgs" "fdsafa" ...
...
我想将每个列表导出到其自己的csv文件中,文件名是列表索引.我正在尝试使用 lapply
而不是for循环来做到这一点,这可能吗?我遇到的困难是如何从 FUN
内部提取列表索引(在这种情况下为名称)?例如,如果我要随机命名它们,则可以执行以下操作:
I'd like to export each list into its own csv file with the filename being the list index. I'm trying to do it using lapply
instead of a for loop, is that possible? The difficulty for me is how do I extract the list index (or name in this case) out inside of the FUN
? For example, if I were to name them randomly I can do this:
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
Edit2 :较短的示例:(←这个比较明智)
Shorter sample: (← this one is more sensible)
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"
))
推荐答案
您不能.一种技巧是使用 lapply
遍历名称,也可以使用 Map
做类似的事情
You can't. One trick is to use lapply
to loop over the names or you can use Map
to do something like
Map(function (name, data)
write.table(data, paste0(name, ".csv"),
sep=",", col.names=F, row.names=F)
, names(lists), lists)
这篇关于如何在lapply的FUN中提取列表项的索引或名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!