[R] difference between foo$a[2] <- 1 and foo[2,"a"] <- 1

Rebecca Hiller hillerrv at gmail.com
Wed Nov 2 17:12:17 CET 2011


Hallo 

Can anyone tell me the difference between

foo$a[2] <- 1 and foo[2,"a"] <- 1 ?

I thought that both expressions are equivalent, but when I run the following example, there is obviously a difference.


> foo <- data.frame(a=NA,b=NA)
> foo
   a  b
1 NA NA
> foo$a[1] <- 1
> foo$b[1] <- 2
> foo$a[2] <- 1
Error in `$<-.data.frame`(`*tmp*`, "a", value = c(1, 1)) : 
  replacement has 2 rows, data has 1
> foo[2,"a"] <- 1
> foo
  a  b
1 1  2
2 1 NA

Thanks,
Rebecca Hiller


--
ETH Zürich
Rebecca Hiller
Institute of Agricultural Sciences
LFW A2
Universitätsstrasse 2
8092 Zürich
SWITZERLAND

rebecca.hiller at ipw.agrl.ethz.ch
http://www.gl.ethz.ch/

+41 44 632 31 90 Telefon
+41 44 632 11 53 Fax



More information about the R-help mailing list