Xst67
Xst67

Reputation: 11

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.

Upvotes: 0

Views: 57

Answers (2)

akrun
akrun

Reputation: 887118

May be this helps:

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

Upvotes: 0

Carl Witthoft
Carl Witthoft

Reputation: 21502

You can do this directly with the matrix command:

x <- 1:36

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

Upvotes: 1

Related Questions