简体   繁体   中英

Create a new column based on the values in another column (in R)

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
library(dplyr)
df %>% mutate(qc = case_when(cl %in% c(19,12,16) ~ 'bad',
                             TRUE ~ 'good')
              )

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

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM