wol*_*oor 2 merge r append matrix dataframe
因此,我想要做的事情很难说清楚但非常简单,我可以很容易地告诉你.标题是我对verbage的最佳猜测,编辑指定.
set.seed(1)
theta=matrix(rnorm(6,0,1),2,3)
M = c( 0 , 0 , 0 , 0, 1 ,
1, 0 , 0 , 0 , 1,
2 , 0 , 0 , 0, 2,
0 , 1 , 0 , 0 ,2,
1 , 1 , 0 , 0, 3,
0 , 2 , 0 , 0, 3)
M = matrix(M, nrow = 6,ncol= 5,byrow=T)
theta
[,1] [,2] [,3]
[1,] 0.4418121 1.962053 2.236691
[2,] 1.0931398 1.273616 1.050373
M
prod11 prod12 prod21 prod22 d
1 0 0 0 0 1
2 1 0 0 0 1
3 2 0 0 0 2
4 0 1 0 0 2
5 1 1 0 0 3
7 0 2 0 0 3
OUTPUT DESIRED
prod11 prod12 prod21 prod22 d theta1 theta2
1 0 0 0 0 1 0.4418121 1.0931398
2 1 0 0 0 1 0.4418121 1.0931398
3 2 0 0 0 2 1.962053 1.273616
4 0 1 0 0 2 1.962053 1.273616
5 1 1 0 0 3 2.236691 1.050373
7 0 2 0 0 3 2.236691 1.050373
Run Code Online (Sandbox Code Playgroud)
我会用data.table
:
setDT(M)
M[, paste0("theta",1:2) := as.data.table(t(theta[, d]))]
> M
V1 V2 V3 V4 V5 theta1 theta2
1: 0 0 0 0 1 -1.2341141 0.4675928
2: 1 0 0 0 1 -1.2341141 0.4675928
3: 2 0 0 0 2 -0.6186437 1.5602801
4: 0 1 0 0 2 -0.6186437 1.5602801
5: 1 1 0 0 3 0.1233480 -0.3746259
6: 0 2 0 0 3 0.1233480 -0.3746259
Run Code Online (Sandbox Code Playgroud)
我们需要as.data.table
或as.data.frame
因为as.list
破坏了矩阵结果的维度,而且:=
会产生unlist
什么t(theta[, d])
如果M
确实存储为矩阵(由于您没有命名其尺寸,因此不清楚),我建议您使用它将其存储为data.table
(或data.frame
)M <- data.table(M)
.
为了完整起见,这里有一个纯粹以矩阵表示法的解决方案:
M <- cbind(M, t(theta[, M[, "d"]]))
Run Code Online (Sandbox Code Playgroud)