我想在数据框中创建一个新列,其中数据框的单元格将取决于条件。这是一些可复制的代码:
a <- c("Boy","Girl","Dog","Cat")
b <- c("1","2","3","4")
df <- data.frame(a,b)
if(df$a=="Boy"|df$b=="Girl"){
df$Type <- "Human"
}
else(
df$Type <- "Animal"
)
# This is what I would like to achieve :
df$Type <- c("Human","Human","Animal","Animal")
但是执行条件时,这是我得到的错误消息:
Warning message:
In if (df$a == "Boy" | df$b == "Girl") { :
condition has a length > 1 only the first element is used
使用dplyr::case_when
library(dplyr)
df %>%
mutate(type = case_when(
a %in% c("Boy", "Girl") ~ "Human",
TRUE ~ "Animal"
)
)