给定数据框和表中定义的一组规则。
df <- rbind(c("blue","M",9),c("blue","F",11))
colnames(df)<-c("eyes","gender","age")
rule <- rbind(c("blue","M","<10",1),c("blue","M",">10",2),c("blue","F","<10",3),c("blue","F",">10",4))
colnames(rule)<-c("eyes","gender","age","category" )
R中是否有办法在不重写if else脚本的情况下应用规则?
结果应如下所示:
eyes gender age category
"blue" "M" 9 1
"blue" "F" 11 4
答案 0 :(得分:4)
require(magrittr); require(dplyr)
# Convert to data.frame
rule %<>% data.frame(stringsAsFactors = F)
df %<>% data.frame(stringsAsFactors = F)
#left join on eyes and gender, then remove rows where age doesn't match
result <- df %>%
left_join(rule, by = c('eyes', 'gender'))%>%
filter(paste(age.x, age.y) %>% sapply(function(x) eval(parse(text = x)))) %>%
select(-age.y)