[R] puzzling behavior of within
Bert Gunter
gunter.berton at gene.com
Thu Jun 13 18:11:40 CEST 2013
Why are you surprised? It has nothing to do with within() . ?"[<-"
> x <- 0
> g <- 1:2
> x[g==1]<- 5
> x
[1] 5 NA
-- Bert
On Thu, Jun 13, 2013 at 9:00 AM, Ista Zahn <istazahn at gmail.com> wrote:
> Hi all,
>
> In answering a question yesterday about avoiding repeatedly typing the
> name of a data.frame when making modifications to it I discovered the
> following unexpected behavior of within:
>
> mtcars <- within(mtcars, {
> x <- 0
> x[gear==4] <- 1
> })
>
> generates a column named x in mtcars equal to 1 if gear equals 4, and
> NA otherwise. What happend to my zeros? I thought maybe you just can't
> modify an object more than once, but that is not true:
>
> mtcars <- within(mtcars, {
> x <- 0
> x[gear==4] <- 1
> x[gear==3] <- 2
> })
>
> returns a data.frame in with the x column is 1 if gear is 4, 2 if gear
> is 3, and NA otherwise. What is going on here?
>
> Surprised by these results I tried a few other things, and found
> another surprising behavior:
>
> mtcars <- within(mtcars, {
> x <- 0
> x[1] <- 1
> })
>
> generates a column named x in mtcars equal to 1. But I thought I said
> only change the first value to one! What happend?
>
> I've been reading and re-reading the documentation, but I can't see
> anything that explains these results.
>
> Thanks for any insight,
> Ista
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
--
Bert Gunter
Genentech Nonclinical Biostatistics
Internal Contact Info:
Phone: 467-7374
Website:
http://pharmadevelopment.roche.com/index/pdb/pdb-functional-groups/pdb-biostatistics/pdb-ncb-home.htm
More information about the R-help
mailing list