[英]I can not save the for loop of the sequential results in R?
My for
loop algorithm has always different sizes, because of the different outputs of the seq
, for that reason, I can't save the results.我的for
循环算法总是有不同的大小,因为seq
输出不同,因此我无法保存结果。 How can I do that?我怎样才能做到这一点? I am stuck on the mat[?,?]
part of the loop, please look at the example below.我被卡在循环的mat[?,?]
部分,请看下面的例子。 How can I do that?我怎样才能做到这一点?
d<-data.frame(L1=c(1,6,8), L2=c(3,14,22))
mat<-matrix(c(0),15,2)
for (i in 1:nrow(d)) {
x1<-seq(d$L1[i],d$L2[i],2)
x1
for (k in seq_along(x1[-1])) {
L1<- x1[k]
L2<- x1[k+1]
mat[?,]<- c(L1+L2,L1-L2)
}
}
In addition, what do you recommend for the nrow
of the initial matrix mat
(it is 15 here).另外,你对初始矩阵mat
的nrow
有什么建议(这里是15)。
The saving outputs will be, for i<-1
and k<-1
保存输出将为,对于i<-1
和k<-1
mat[1,]<-c(4,-2),
for i<-2
and k<-1, k<-2, k<-3
and k<-4
对于i<-2
和k<-1, k<-2, k<-3
和k<-4
mat[2,]<-c(14,-2), mat[3,]<-c(18,-2),mat[4,]<-c(22 ,-2) and mat[5,]<-c(22 ,-2)
and so on..等等..
Try this approach using apply
which will :使用apply
尝试这种方法,它将:
do.call(rbind, apply(d, 1, function(x) {
x1 <- seq(x[1], x[2], 2)
cbind(head(x1, -1) + tail(x1, -1), head(x1, -1) - tail(x1, -1))
}))
# [,1] [,2]
# [1,] 4 -2
# [2,] 14 -2
# [3,] 18 -2
# [4,] 22 -2
# [5,] 26 -2
# [6,] 18 -2
# [7,] 22 -2
# [8,] 26 -2
# [9,] 30 -2
#[10,] 34 -2
#[11,] 38 -2
#[12,] 42 -2
+
and -
operations are vectorised so you don't need a for
loop to do that. +
和-
操作是矢量化的,所以你不需要for
循环来做到这一点。 Using head
and tail
we select combination of current value and next value.使用head
和tail
我们选择当前值和下一个值的组合。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.