我想建议如何根据以下数据集编写新列:
df <- data.frame(AA = c("3454","345","5","345","567","79","43","2342","231","234","232","24"),
BB = c(123, 345, 7567, 234, 8679, 890, 812, 435345, 567, 568, 786, 678),
CC = c(1, 2, 6, 8, 22, 33, 56, 2, 34, 45, 45, 65), stringsAsFactors = F)
并且我想根据以下条件创建一个名为“ new”的新列:
Group1 = AA> 300&BB> 2000&CC <5
第2组= AA≥20&BB≤700&CC> 60但≤70
谢谢!
答案 0 :(得分:2)
case_when()
中的 dplyr
旨在避免使用嵌套的ifelse()
。
library(dplyr)
df %>%
mutate(new = case_when(
AA > 300 & BB > 2000 & CC < 5 ~ "Group1",
AA >= 20 & BB <= 700 & CC > 60 & CC <=70 ~ "Group2",
TRUE ~ "other"
))
答案 1 :(得分:1)
您可以尝试以下方法:
library(dplyr)
df %>% mutate(Group=ifelse(AA>300 & BB>2000 & CC<5,'Group1',
ifelse(AA>=20 & BB<=700 & (CC > 60 & CC<=70),'Group2',NA))) -> df1