[R] Setting elements in data frame
Kaspar Pflugshaupt
pflugshaupt at cirsium.ethz.ch
Thu Feb 22 16:10:20 CET 2001
On Thursday 22 February 2001 15:29, Peter Dalgaard BSA wrote:
> Hmmmm... How about
>
> recode<-function(x,value,replacement){
> x[if (is.na(value)) is.na(x) else x==value] <- replacement
> x
> }
> s <-sapply(x,is.numeric)
> x[s] <- lapply(x[s], recode, 6, 6000)
> x[s] <- lapply(x[s], recode, NA, 1000)
Getting better and better!
While we're at it: Why would the following not work (it's the first version I
tried):
data.frame(lapply(x,function(z) ifelse(z==6,6000,z)))
It does the replacement all right, but the factor column gets converted to
integer. Looking at ?ifelse, I find that
`ifelse' returns a value with the same shape as `test' which is
filled with elements selected from either `yes' or `no' depending
on whether the element of `test' is `TRUE' or `FALSE'. If `yes' or
`no' are too short, their elements are recycled.
So could it be that because 6 (an integer) is present in the comparison, the
result _will_ be integer no matter what class z is? The help doesn't say so,
but I might overlook something basic. Still, checking this out:
> data.frame(lapply(x,function(x) ifelse(x==6.0,6000.0,x)))
# would give float results, if above were true
S1 N1 N2
1 2 2 6000
2 3 4 NA
3 4 6000 0
4 1 9 6000
still gives integer results. And the problem does not lie with the data.frame
conversion:
> str(lapply(x, function(x) ifelse(x==6,6000,x)))
List of 3
$ S1: int [1:4] 2 3 4 1
$ N1: num [1:4] 2 4 6000 9
$ N2: num [1:4] 6000 NA 0 6000
puzzled-ly yours
Kaspar Pflugshaupt
--
Kaspar Pflugshaupt
Geobotanical Institute
ETH Zurich, Switzerland
http://www.geobot.umnw.ethz.ch
mailto:pflugshaupt at geobot.umnw.ethz.ch
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !) To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._
More information about the R-help
mailing list