Reputation: 463
I have a df as shown below. I would like to generate a separate column "qc" where the output is based on column "cl". More detailed: if the value in cl is 19, 12 or 16 display in column "qc" "bad" if the value is different that the 3 numbers given then put "good".
df
cl
a 19
b 12
c 16
d 1
c 2
result
cl qc
a 19 bad
b 12 bad
c 16 bad
d 1 good
c 2 good
Upvotes: 0
Views: 72
Reputation: 141
this specific case could also easily be done with ifelse()
:
df <- data.frame(cl=c(19,12,16,1,2))
df$qc <- ifelse(df$cl==19|df$cl==12|df$cl==16,
"bad",
"good")
# cl qc
# 1 19 bad
# 2 12 bad
# 3 16 bad
# 4 1 good
# 5 2 good
maybe more intuitive. ~cheers chris
Upvotes: 2
Reputation: 39647
You can use the result of %in%
to subset c("good", "bad")
.
df$qc <- c("good", "bad")[1 + df$cl %in% c(12L, 16L, 19L)]
# cl qc
#a 19 bad
#b 12 bad
#c 16 bad
#d 1 good
#e 2 good
Upvotes: 1
Reputation: 76402
Here is a base R solution with %in%
.
bad <- c(12, 16, 19)
df1$qc <- "good"
df1$qc[df1$cl %in% bad] <- "bad"
df1
# cl qc
#a 19 bad
#b 12 bad
#c 16 bad
#d 1 good
#e 2 good
Data
df1 <- read.table(text = "
cl
a 19
b 12
c 16
d 1
e 2
", header = TRUE)
Upvotes: 1
Reputation: 196
library(dplyr)
df %>% mutate(qc = case_when(cl %in% c(19,12,16) ~ 'bad',
TRUE ~ 'good')
)
Upvotes: 2