简体   繁体   中英

For in function in R for different groups of rows

I have the following R objects:

y <- sample(c(0,2,2),1000,replace=T)
X <- matrix(runif(2000,0,2),ncol=2,byrow=T)*2

XX = t(X)%*%X
XY = as.numeric(t(X)%*%y)
YY = as.numeric(t(y)%*%y)

How can I run it to get several XX, XY and YY objects calculated with the first 10 rows, others with the rows 11 to 20, etc...?? Any ideas with a for in loop? Thank you!

We can create lists to store different outputs. Create a sequence with a step of 10 and calculate the result in for loop.

len <- length(y)/10
XX_list <- vector('list', len)
XY_list <- vector('list', len)
YY_list <- vector('list', len)
vals <- seq(1, length(y), 10)

for(i in seq_along(vals)) {
  inds <- vals[i]:(vals[i] + 9)
  XX_list[[i]] <- t(X[inds, ]) %*% X[inds, ]
  XY_list[[i]] =  as.numeric(t(X[inds, ])%*% y[inds])
  YY_list[[i]] = as.numeric(t(y[inds])%*% y[inds])
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM