使用“if-else”结构在data.frame中创建新列

使用“if-else”结构在data.frame中创建新列,r,dataframe,conditional-statements,R,Dataframe,Conditional Statements,我想在dataframe中创建一个新列,其中dataframe的单元格取决于一个条件。以下是一些可复制的代码: 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

我想在dataframe中创建一个新列,其中dataframe的单元格取决于一个条件。以下是一些可复制的代码:

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")
在以下情况下使用dplyr::case\u


在%cBoy,Girl中使用df$a%而不是|在%cBoy,Girl中键入ifdf$a%时更像df$Type df$Type{df$Type@Axeman是的,很抱歉键入错误,我的意思是df$a==Girl如果只测试了一个条件,您可以使用base ifelse;当
Warning message:
In if (df$a == "Boy" | df$b == "Girl") { :
  condition has a length > 1 only the first element is used
library(dplyr)

df %>% 
  mutate(type = case_when(
    a %in% c("Boy", "Girl") ~ "Human",
    TRUE ~ "Animal"
  )
)