How to replace values by NA using element encoding (and not position)?

2

I am having difficulty replacing values in a vector by NA, but using the treatment coding (not the position). A simple and hypothetical example of my problem is (my dataset is very large and I have several sets, so I can not do manual):

filhos <- c(1, 3, 5, 6, 8, 10, 11, 12, 15)
peso <- c(55, 58, 76, 42, 68, 80, 47, 55, 85)
dados <- as.data.frame(cbind(filhos, peso))
set <- c(3, 6, 11)
New <- dados$peso; New
    [1] 55 58 76 42 68 80 47 55 85 

What I want is the result:

    [1] 55 NA 76 NA 68 80 NA 55 85 

where NA refers to children 3, 6, and 11. I tried some options that did not work, like:

New[set] <- NA; New            # usa a posicao e nao o codigo do individuo
    [1] 55 58 NA 42 68 NA 47 55 85 NA NA       

# ou
ifelse(dados$filhos==set, NA, New)   # erro = vetor New nao tem a mesma dimensao de set 

Could someone please help me?

    
asked by anonymous 10.08.2016 / 16:32

1 answer

3

Use the command %in% in the comparison:

filhos <- c(1, 3, 5, 6, 8, 10, 11, 12, 15)
peso <- c(55, 58, 76, 42, 68, 80, 47, 55, 85)
dados <- as.data.frame(cbind(filhos, peso))
set <- c(3, 6, 11)
New <- dados$peso; New

ifelse(dados$filhos %in% set, NA, New)
[1] 55 NA 76 NA 68 80 NA 55 85

The %in% checks whether each element of a vector is contained within another vector.

    
10.08.2016 / 16:48