[R] Replacing rows in a data frame

Brant Inman brant.inman at me.com
Mon Jan 17 21:29:57 CET 2011


R-helpers,

Below is a simple example of some output that I am getting while trying to work with a data frame in R 2.12.1 for Mac.

-----
> testdat <- data.frame(matrix(ncol=10, nrow=10))
> colnames(testdat) <- c('a','b','c','d','e','f','g','h','i','j')
> testdat[seq(1,10,3),] <- c(1,0,0,0,0,0,0,0,0,0)

> testdat
    a  b  c  d  e  f  g  h  i  j
1   1  0  0  0  0  1  0  0  0  0
2  NA NA NA NA NA NA NA NA NA NA
3  NA NA NA NA NA NA NA NA NA NA
4   0  0  0  0  0  0  0  0  0  0
5  NA NA NA NA NA NA NA NA NA NA
6  NA NA NA NA NA NA NA NA NA NA
7   0  0  1  0  0  0  0  1  0  0
8  NA NA NA NA NA NA NA NA NA NA
9  NA NA NA NA NA NA NA NA NA NA
10  0  0  0  0  0  0  0  0  0  0

-----

The output is not what I would have anticipated.  Since seq(1,10,3) gives the vector [1 4 7 10], I expected rows 1, 4, 7 and 10 of the data.frame "testdat" to contain the same data, a 1 for variable 'a' and zeros for all other variables.  I guess I assumed the assigment would proceed by rows, but it appears from the resulting output to be proceeding by columns. Can someone point out how I can modify this simple code so that the assignments proceed by rows?

Thank you.

Brant



More information about the R-help mailing list