How do I extract the index or name of the list item within FUN of lapply?

本小妞迷上赌 提交于 2019-12-11 03:14:06

问题


Say I have a list of lists lists:

> lists
$a
[1] "fas"    "asdfas"    "adfaff" ...

$b
[1] "jnfg"   "gfsdgs"    "fdsafa" ...

...

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))

Edit: Sample 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"
))

回答1:


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)



回答2:


You can use mapply

mapply(function(name, x) {
    write.table(x, paste0(name, ".csv"), sep=",", col.names=F, row.names=F)
}, names(lists), lists)

Or actually using lapply is also possible

lapply(names(lists), function(name) {
    write.table(lists[name], paste0(name, ".csv"), sep=",", col.names=F, row.names=F)
})


来源:https://stackoverflow.com/questions/25006076/how-do-i-extract-the-index-or-name-of-the-list-item-within-fun-of-lapply

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!