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

Pancho Mulongeni p.mulongeni at namibia.pharmaccess.org
Mon Oct 22 09:50:13 CEST 2012

```Perfect, thanks

-----Original Message-----
Sent: Wednesday, October 17, 2012 9:49 PM
To: Pancho Mulongeni
Cc: r-help at r-project.org
Subject: Re: [R] Setting all rows of a certain level to NA in a factor

Hello,

Try the following.

b <- factor(ifelse(!B20_A %in% c("No ", "Yes"), NA, B20_A), labels = c("No ", "Yes"))
str(b)

Hope this helps,

Em 17-10-2012 15:51, Pancho Mulongeni escreveu:
> 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, 1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 1L, 1L, 3L, 1L, 1L, 4L, 1L, 3L,
> 1L, 4L, 4L, 3L, 4L, 1L, 1L, 4L, 4L, 4L, 4L, 4L, 3L, 3L, 1L, 1L,
> 1L, 4L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 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