简体   繁体   中英

How to make a matrix from a given vector by using for loop

I am trying to make a $n\\times 4$ matrix by retrieving the n-th four elements in a given vector. Since I am new to R , don't know how to use loop functions properly.

My code is like

x<-runif(150,-2,2)
x1<-c(0,0,0,0,x)
for (i in 0:150)
 {ai<-x1[1+i,4+i]
 }

However, I got: Error in x1[1 + i, 4 + i] : incorrect number of dimensions.

I also want to combine these ai into a matrix, and each ai will be the i+1-th row of the matrix. Guess I should use the cbind function?

Any help will be appreciated. Thanks in advance.

You can do this directly with the matrix command:

x <- 1:36

xmat<-matrix(x,nr=9,byrow=TRUE)

May be this helps:

n <- length(x1)-1
res <- sapply((4:n)-3, function(i) x1[(i+3):i])
dim(res)
#[1]   4 150

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