[R] Recode Variable

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


Le jeudi 12 avril 2012 à 11:08 +0200, David Studer a écrit :
> Hello everybody,
> 
> I know this is pretty basic stuff, but could anyone explain me how to
> recode a single value of a variable
> into a missing value?
> 
> I used to do it like this:
> 
> myData[myData$var1==5;"var1"]<-NA             # recode value "5" into "NA"
> 
> But the column "var1" already contains NAs, which
> results in the following error message:
> 
> "missing values are not allowed in subscripted assignments of data frames"
> 
> Thank you very much for any advice!
You can just do this:
myData <- data.frame(var1=1:10)
myData$var1[2]<-NA
myData[myData$var1 == 5, "var1"] <- NA # Fails
myData$var1[myData$var1 == 5] <- NA # Works
myData
   var1
1     1
2    NA
3     3
4     4
5    NA
6     6
7     7
8     8
9     9
10   10


Regards



More information about the R-help mailing list