简体   繁体   中英

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? 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. With your example, you can get the output with this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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