How to check if a value is contained in another list

Asked

Viewed 35 times

5

I need to check if the value of a column is contained in a list and, if it is, copy its value to a third column.

Let’s take the example:

df <- data.frame(Nome = c("Maria", "Pedro", "João","Mário"),
       Situação = c("regular","irregular","regular","Isento"),
       valor = c(1,2,1,5),
       resultado = c(0,0,0,0))

inserir a descrição da imagem aqui

lista <- list(c("regular","Isento"))

Now I need to check if the value (row by row) of the Situation column is contained in the list and bring the result in the corresponding row of the result column

I thought I’d do with for:

for (i in seq(nrow(df))) {
  if (**???**) {
    df[i,4] <- Base[i,3]
  }
}

and the result would be:

inserir a descrição da imagem aqui

How do I write this condition on if for R to verify that the value is contained in the list?

1 answer

6

One can do what the question asks with a logical index created with %in%.

i <- df$Situação %in% unlist(lista)
df$resultado <- 0
df$resultado[i] <- df$valor[i]

df
#   Nome  Situação valor resultado
#1 Maria   regular     1         1
#2 Pedro irregular     2         0
#3  João   regular     1         1
#4 Mário    Isento     5         5

Browser other questions tagged

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