Home > Enterprise >  Change value of column if value exists in list
Change value of column if value exists in list

Time:10-29

I have a R dataframe that is structured like this :

indx <- as.factor(c('A01','A02','A03','B01','B02','B03'))
data <- runif(6,0,10)
valid <- rep(TRUE, 6)

df <- data.frame(indx, data, valid)

  indx     data valid
1  A01 6.534581  TRUE
2  A02 4.996695  TRUE
3  A03 3.328804  TRUE
4  B01 2.342048  TRUE
5  B02 9.928362  TRUE
6  B03 5.484037  TRUE

I also have a list of indx values when are not valid.

invalid_list <- as.factor(c('A02','B03'))

How can I change the value of valid to be FALSE if the indx exists in the invalid_list?

Result should look like this :

  indx     data valid
1  A01 6.534581  TRUE
2  A02 4.996695  FALSE
3  A03 3.328804  TRUE
4  B01 2.342048  TRUE
5  B02 9.928362  TRUE
6  B03 5.484037  FALSE

CodePudding user response:

We may use %in% and assign the matching ones to FALSE in 'valid'

df$valid[df$indx %in%invalid_list] <- FALSE

CodePudding user response:

A solution based on dplyr:

library(dplyr)

df %>% 
  mutate(valid = ifelse(indx %in% invalid_list, FALSE, valid))
  • Related