R-替换嵌套为-嵌套列表 [英] R - Replace nested for - Nested lists
本文介绍了R-替换嵌套为-嵌套列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在R中建立了一个列表列表,而让它起作用的唯一方法是使用嵌套的fors.问题在于,它们最多需要4秒钟才能运行,因此运行速度极慢.这就是我构建它们的方式:
I build a list of lists in R and the only way I got it to work is with nested fors. The problem is that they take up to 4 seconds to run therefore it's extreme slow. This is how I build them:
tt = vector("list", length(dp$id))
for (idx in seq_along(dp$id)) {
pos = dp$id[idx]
position = dp[id == pos]$pdim
tt[[idx]] = list(
a = unbox(pos),
b = list()
)
tmp = positionData[positionId == position]
tls = vector("list", nrow(tmp))
if (nrow(tmp)) {
for (row in 1:nrow(tmp)) {
tls[[row]] = list(
c = unbox(tmp[row]$d),
d = unbox(tmp[row]$c)
)
}
tt[[idx]]$b = tls
}
}
有没有一种方法可以同时替换这两种方法以更快地建立列表?
Is there a way to replace both for's to build the lists faster?
示例数据
dp = data.table(id =c(5632,5633, 5634, 5635, 5636), pdim = c(2103, 2048, 2093, 2069, 2086))
positionData = data.table(
positionId = c(2048, 2069, 2086, 2093, 2103, 2048, 2069, 2086, 2093, 2103, 2048, 2069, 2086, 2093, 2103, 2048, 2069, 2086, 2093, 2103, 2048, 2069, 2086, 2093, 2103, 2048),
d = c(0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0),
c = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0))
推荐答案
每个tt子列表(总共5个)的b
是data.frame
而不是列表是怎么回事?如果您可以忍受这一点,那么您肯定可以避免第二个循环:
How about b
for each tt sublist (5 in total) is a data.frame
and not a list? If you can live with this you surely can avoid the second loop:
library(dplyr)
tt = list()
for (idx in seq_along(dp$id)) {
pos = dp$id[idx]
position= dp[id == pos]$pdim
tt[[idx]] = list(a = pos,b = list())
tmp = positionData[positionId == position]
tls<-transmute(tmp,c=d,d=c)
tt[[idx]]$b = tls
}
这篇关于R-替换嵌套为-嵌套列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文