在具有“ if else”结构的data.frame中创建新列

问题描述 投票:0回答:1

我想在数据框中创建一个新列,其中数据框的单元格将取决于条件。这是一些可复制的代码:

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
r dataframe conditional-statements
1个回答
0
投票

使用dplyr::case_when

library(dplyr)

df %>% 
  mutate(type = case_when(
    a %in% c("Boy", "Girl") ~ "Human",
    TRUE ~ "Animal"
  )
)
© www.soinside.com 2019 - 2024. All rights reserved.