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

Berend Hasselman bhh at xs4all.nl
Wed Oct 17 21:43:05 CEST 2012

```On 17-10-2012, at 16:51, Pancho Mulongeni wrote:

> 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.

No it is not. 'No ' i.e. No followed by a space is a level.
Change "No " to "No" in your object.

Berend

> #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, 3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 4L, 1L, 3L, 3L, 1L,
> 1L, 3L, 3L, 1L, 4L, 1L, 4L, 1L, 3L, 3L, 1L, 1L, 1L, 1L, 3L, 4L,
> 3L, 3L, 3L, 4L, 4L, 3L, 4L, 1L, 3L, 1L, 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
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help