Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning values to rows from a vector

Tags:

r

I have a relatively simple question that my colleagues and I cannot figure out. I have a vector of values that I would like to paste into all of the rows in my dataset within a certain range of columns.

The following code works if I assign values row by row:

data[1, 1:10] <- myvector
data[2, 1:10] <- myvector

If I attempt to assign values over the total number of rows, the same code doesn't work correctly:

data[1:nrows(data), 1:10] <-myvector

It appears that the values in the vector are being filled in vertically, rather than horizontally. The best we've come up with is a workaround, which is not ideal given that I have 20,000 rows in my data.

for (i in 1:nrow(data)){
     data[i, 1:10] <-myvector
}

There must be some simple explanation for what is wrong. Please help!

like image 332
roody Avatar asked Jul 11 '12 00:07

roody


1 Answers

Assigning a vector to a matrix like that fills them in vertically, as you observed. But you can work around this by assigning the appropriate vector:

 data[, 1:10] = rep(myvector, each=NROW(data))
like image 127
David Robinson Avatar answered Sep 28 '22 05:09

David Robinson