ana_gg
ana_gg

Reputation: 370

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!

Upvotes: 0

Views: 21

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389325

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])
}

Upvotes: 2

Related Questions