R中的嵌套循环用于创建矩阵数组 [英] Nested Loop in R for creating arrays of matrices
本文介绍了R中的嵌套循环用于创建矩阵数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用以下数据集,我想制作一个3阶(T,T1,T2和T3中的三列)2阶(无行数)乘以11(fu.time的长度)的矩阵的数组. /p>
With the following data set, I would like to make an array of 3(three columns in T, T1,T2 and T3) matrices of order 2( no of rows) by 11(length of fu.time).
b0=data.frame(b0_1=c(11.41,11.36),b0_2=c(8.767,6.950))
b1=data.frame(b1_1=c(0.8539,0.9565),b1_2=c(-0.03179,0.06752))
b2=data.frame(b2_1=c(-0.013020 ,-0.016540),b2_2=c(-0.0002822,-0.0026720))
T.val=data.frame(T1=c(1,1),T2=c(1,2),T3=c(2,1))
d_data=cbind(b0,b1,b2,T.val)
fu.time=seq(0,1,by=0.1)
pat=ncol(T.val)
nit=2
我尝试了以下循环,很遗憾,它无法正常工作.
I tried the follwoing loop, Unfortunately it is not working.
pt.array=array(NA, dim=c(nit,length(fu.time),pat))
for ( it.er in 1:nit){
for ( ti in 1:length(new.time_2q.RI)){
for (pt in 1:pat){
pt.array[it.er,ti,pt]=b0[T.val[it.er,pt]]+b1[T.val[it.er,pt]]*fu.time[ti]+b2[T.val[it.er,pt]]*fu.time[ti]^2
}
}
}
这个概念是,如果T1
取值1
,则取b0,b1 and b2
的第一列.如果任何T
采用值2
,则采用相应的第二列值b0,b1, and b2
.
The concept is, if T1
takes value 1
, then the first column of b0,b1 and b2
are taken. If any of the T
takes value 2
then the corresponding second column value of b0,b1, and b2
are taken.
推荐答案
以下嵌套循环正在工作.
Following nested loop is working.
pt.array1=array(NA, dim=c(nit,length(fu.time),pat))
for ( it.er in 1:nit){
for ( ti in 1:length(fu.time)){
for (pt in 1:pat){
pt.array1[it.er,ti,pt]=b0[it.er,T.val[it.er,pt]]+b1[it.er,T.val[it.er,pt]]*fu.time[ti]+b2[it.er,T.val[it.er,pt]]*fu.time[ti]^2
}
}
}
如果有的话,也可以选择其他方法.
Alternative approaches are appreciated if any.
这篇关于R中的嵌套循环用于创建矩阵数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文