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

Asked

Viewed 709 times

2

I’m having trouble replacing values on a vector with NA, but using treatment coding (not position). A simple and hypothetical example of my problem is (my data set is too large and I have several sets, so I can’t 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 

in which the AN refers to sons 3, 6, and 11. I tried some options that didn’t work out, 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 help me, please?

1 answer

3


Use the command %in% in 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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.