[R] Recode Variable

Milan Bouchet-Valat nalimilan at club.fr
Thu Apr 12 11:58:45 CEST 2012


Le jeudi 12 avril 2012 à 12:29 +0300, Tal Galili a écrit :
> Hi David,
> You bring up a good question.  I am not sure what is the "right" way to
> solve it.  But here is a simple solution I put together:
> 
> x = c(1:10,5)
> y = x
> x[c(2,3)] <- NA
> 
> # reproducing the problem:
> y[x==5]
> 
> na2F <- function(x) {
>     x2 <- x
>     x2[is.na(x)] <- F
>     x2
> }
> na2F(x==5)
> 
> # "solved"
> y[na2F(x==5)]
> 
> 
> I'd be happy to see other solutions to it.
You can simply use the built-in function which() for this, since it
removes NAs, only returning the position of TRUE elements:
which(c(NA, 1:10 == 5))
[1] 6


My two cents



More information about the R-help mailing list