[R] Setting all rows of a certain level to NA in a factor

Pancho Mulongeni p.mulongeni at namibia.pharmaccess.org
Wed Oct 17 16:51:01 CEST 2012


Hello everyone.
My task is set certain levels (that is all rows of that level) as missing values in factor B20_A.
Excuse the notation, it happens to be a question number in a survey.
So I thought it would work easily by defining the levels
and their labels using the 'factor' function.

> levels(B20_A)
[1] "   " "5.6" "No " "Yes"
#as you can see 'No' is a level.
#I below define the levels, I expect 5.6 and blank to be set as NA
B20_A<-factor(B20_A,levels=c('No','Yes'),labels=c('No','Yes'))
summary(B20_A)

  No  Yes NA's 
   0  149  580 
to my surprise, 'No' is also set as NA, why is this happening?

I am a frequent SPSS user and I am surprised that this operation does not seem to be so straight forward in R.
Thanks
my object is defined below.
structure(c(4L, 1L, 4L, 4L, 1L, 3L, 1L, 3L, 1L, 1L, 1L, 3L, 1L, 
3L, 3L, 1L, 1L, 4L, 1L, 4L, 4L, 3L, 1L, 3L, 4L, 3L, 4L, 3L, 3L, 
1L, 1L, 3L, 1L, 3L, 4L, 4L, 3L, 1L, 1L, 4L, 4L, 3L, 3L, 3L, 1L, 
3L, 3L, 3L, 1L, 4L, 1L, 4L, 1L, 1L, 1L, 3L, 3L, 1L, 4L, 4L, 3L, 
1L, 1L, 4L, 4L, 3L, 1L, 1L, 3L, 1L, 4L, 3L, 3L, 3L, 1L, 4L, 3L, 
3L, 4L, 4L, 4L, 4L, 1L, 3L, 1L, 1L, 1L, 1L, 3L, 3L, 1L, 3L, 1L, 
1L, 1L, 3L, 1L, 1L, 4L, 3L, 1L, 4L, 4L, 4L, 4L, 4L, 3L, 3L, 3L, 
3L, 1L, 3L, 3L, 4L, 3L, 1L, 1L, 1L, 1L, 1L, 3L, 3L, 1L, 1L, 1L, 
4L, 1L, 3L, 3L, 1L, 3L, 1L, 1L, 1L, 1L, 3L, 3L, 3L, 1L, 1L, 1L, 
4L, 4L, 1L, 1L, 1L, 1L, 1L, 3L, 3L, 1L, 1L, 3L, 3L, 4L, 4L, 1L, 
1L, 3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, 1L, 1L, 1L, 4L, 1L, 4L, 
4L, 1L, 3L, 4L, 1L, 1L, 1L, 1L, 3L, 1L, 1L, 1L, 3L, 3L, 1L, 1L, 
1L, 1L, 3L, 4L, 1L, 1L, 3L, 3L, 4L, 4L, 1L, 3L, 1L, 4L, 1L, 3L, 
1L, 1L, 1L, 1L, 3L, 3L, 1L, 3L, 4L, 1L, 1L, 4L, 3L, 1L, 3L, 1L, 
1L, 3L, 1L, 1L, 4L, 1L, 1L, 1L, 4L, 3L, 1L, 3L), .Label = c("   ", 
"5.6", "No ", "Yes"), class = "factor")

Pancho Mulongeni
Research Assistant
PharmAccess Foundation
1 Fouchè Street
Windhoek West
Windhoek
Namibia
 
Tel:   +264 61 419 000
Fax:  +264 61 419 001/2
Mob: +264 81 276 6075



More information about the R-help mailing list