【发布时间】:2018-08-16 13:46:51
【问题描述】:
我在 R 中构建了一个列表列表,我让它工作的唯一方法是使用嵌套 fors。问题是它们最多需要 4 秒才能运行,因此速度非常慢。这就是我构建它们的方式:
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
}
}
有没有办法同时替换两个 for 以更快地构建列表?
编辑:样本数据
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))
【问题讨论】:
-
您能提供一个数据示例吗?
-
我已经编辑了问题并添加了 for 循环中所需的两个 data.tables