我有一个x包含数百万条目的列表.我希望将长度大于1的所有条目放入新列表中z.我怎样才能在R中有效地做到这一点?
我尝试了这段代码,而R只是长时间运行.
z=NULL
for(i in 1:length(x)) {
if(length(x[[i]])!=1) z=list(z,x[[i]])
}
Run Code Online (Sandbox Code Playgroud)
这是您要使用的一种情况vapply:
z <- x[vapply(x, length, integer(1)) > 1L]
Run Code Online (Sandbox Code Playgroud)
以下是基准比较sapply和vapply:
A <- list( x = c(), y = c(1), z = c(1, 2))
B <- A[sample(1:3, 1e7, replace = TRUE)]
system.time(sapply(B, length))
# user system elapsed
# 55.95 0.54 56.50
system.time(vapply(B, length, integer(1)))
# user system elapsed
# 6.78 0.00 6.78
Run Code Online (Sandbox Code Playgroud)