[R] puzzling behavior of within
Ista Zahn
istazahn at gmail.com
Thu Jun 13 18:00:21 CEST 2013
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
More information about the R-help
mailing list