[R] Setting elements in data frame

Kaspar Pflugshaupt pflugshaupt at cirsium.ethz.ch
Thu Feb 22 14:28:42 CET 2001


On Thursday 22 February 2001 12:11, Christian Hoffmann wrote:
> Hi all,
>
> I have a problem which I am biting my teeth into unsuccessfully:
>
>  (x <- data.frame(S1=c("a","b","d","F"),N1=c(2,4,6,9),N2=c(6,NA,0,6)))
>   S1 N1 N2
> 1  a  2  6
> 2  b  4 NA
> 3  d  6  0
> 4  F  9  6
>
> > is.na(x)
>
>      S1    N1    N2
> 1 FALSE FALSE FALSE
> 2 FALSE FALSE  TRUE
> 3 FALSE FALSE FALSE
> 4 FALSE FALSE FALSE
>
> No I want to be able to do:
> 1) Setting all elements == 6 to 6000

Not elegant, nor fast, but works (old BASIC habits die hard):

 for (i in 1:nrow(x))
   for (j in 1:ncol(x))
     if (!is.na(x[i,j]) && x[i,j]==6)
        x[i,j] <- 6000

I'm sure there's a vectorized or otherwise much cleaner solution for this...


> 2) Setting all elements == NA to -1000
> x[is.na(x)] <- -1000

can be done equivalently.

>
>
> What am I missing?

The problem seems to be that you cannot do a matrix subscript (which you 
would do with [is.na(x)] ) on a data frame. This probably is reasonable, 
since it would only work for simple (matrix-like) data frames. You might try 
to work on the data frame column-wise, since columns have the same data.class



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