R 从行号矩阵中获取列中的值
以下是数据设置:R 从行号矩阵中获取列中的值,r,data.table,R,Data.table,以下是数据设置: require(data.table) set.seed(42) pos_mat <- data.table(c1 = sample(1:1000), c2 = sample(1:1000), c3 = sample(1:1000)) data <- data.table(value = rnorm(1000), other_stuff = rnorm(1000)) 以及: 现在pos_mat中的每个元素都响应数据中的行号。我希望创建一个新的data.ta
require(data.table)
set.seed(42)
pos_mat <- data.table(c1 = sample(1:1000), c2 = sample(1:1000), c3 = sample(1:1000))
data <- data.table(value = rnorm(1000), other_stuff = rnorm(1000))
以及:
现在pos_mat中的每个元素都响应数据中的行号。我希望创建一个新的data.table,它的维度与pos_mat相同,但它不包含行号,而是保存数据中的相应值
即,pos_mat[1,.(c1)]的值为915。在data[915,((value)]=0.1702369中,我希望将其存储在新对象中
我觉得有点像:
new <- pos_mat
n <- nrow(pos_mat)
for(i in n) new[i,] <- data[unlist(pos_mat[1,]), value]
new使用较小的数据集
require(data.table)
set.seed(42)
pos_mat <- data.table(c1 = sample(1:10), c2 = sample(1:10), c3 = sample(1:10))
data <- data.table(value = rnorm(10), other_stuff = rnorm(10))
或使用矩阵(使用新的pos_mat
数据集)
res现在更清楚了吗?如果你想保持相同的维度,这应该可以new如果你想将其矢量化,我建议你使用矩阵。像下面这样的东西应该可以工作res我认为你不需要lappy
或任何循环。尝试:通过最有效的数据。表
方法可能是使用集合
如中的(j in names(pos_mat))集合(pos_mat,j=j,value=data[pos_mat[[j]],value])
这些是很好的解决方案,在我的实际数据中,第一个解决方案更快。。。但第二个解决方案运行得足够快(也许更简单一点)。
new <- pos_mat
n <- nrow(pos_mat)
for(i in n) new[i,] <- data[unlist(pos_mat[1,]), value]
require(data.table)
set.seed(42)
pos_mat <- data.table(c1 = sample(1:10), c2 = sample(1:10), c3 = sample(1:10))
data <- data.table(value = rnorm(10), other_stuff = rnorm(10))
for (j in names(pos_mat)) set(pos_mat, j = j, value = data[pos_mat[[j]], value])
pos_mat
# c1 c2 c3
# 1: 1.8951935 1.3201133 1.8951935
# 2: 1.2146747 -1.7813084 -0.2842529
# 3: -2.6564554 -0.1719174 -0.1719174
# 4: -0.3066386 -0.2842529 -1.7813084
# 5: -2.4404669 -2.6564554 0.6359504
# 6: -0.1719174 1.8951935 -2.6564554
# 7: 1.3201133 -2.4404669 1.2146747
# 8: 0.6359504 0.6359504 1.3201133
# 9: -0.2842529 -0.3066386 -0.3066386
# 10: -1.7813084 1.2146747 -2.4404669
res <- data[unlist(pos_mat), value]
dim(res) <- dim(pos_mat)
res
# [,1] [,2] [,3]
# [1,] 1.8951935 1.3201133 1.8951935
# [2,] 1.2146747 -1.7813084 -0.2842529
# [3,] -2.6564554 -0.1719174 -0.1719174
# [4,] -0.3066386 -0.2842529 -1.7813084
# [5,] -2.4404669 -2.6564554 0.6359504
# [6,] -0.1719174 1.8951935 -2.6564554
# [7,] 1.3201133 -2.4404669 1.2146747
# [8,] 0.6359504 0.6359504 1.3201133
# [9,] -0.2842529 -0.3066386 -0.3066386
# [10,] -1.7813084 1.2146747 -2.4404669