简体   繁体   English

R-将功能应用于长列表的最佳方法

[英]R - Best way to apply function to long list

I have a long list object (length in the millions). 我有一个长列表对象(长度以百万计)。 I would like to apply a function to each entry in the list and then return a new augmented list. 我想对列表中的每个条目应用一个函数,然后返回一个新的扩充列表。 Aside from looping from 1 to the length of the list, what would be the best and most efficient way to accomplish this? 除了从1到列表的长度循环外,实现此目的的最佳和最有效的方法是什么? An example of this is below along with the loop I'm currently using. 下面是一个示例以及我当前正在使用的循环。

list1 <- list("zzz yyy xxx", "zzz yyy rrr", "rrr jjj ppp", "eee bbb ccc", "qqq pppp zzz")

change <- function(entry) {
    entry <- strsplit(entry, " ")[[1]]
    aug_entry <- entry[!entry %in% 'zzz']
    return(aug_entry)
}

I'm looking for a better alternative to this... 我正在寻找一个更好的替代方案...

list2 <- list()
for (j in 1:length(list1)) {
    list2[[j]] <- change(list1[[j]])
}

I've looked online and can't seem to find a good solution to this problem, any help is appreciated. 我已经上网了,似乎无法找到解决此问题的好方法,我们将为您提供任何帮助。

I think lapply is what you are looking for. 我认为您正在寻找lapply With your example, you can get the output with this 以您的示例为例,您可以获取输出

list2<- lapply(list1,function(x)change(x))

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

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