我有两个数据帧:酱料和规则。rules有一个名为fieldname的列,它由sauce中的列名组成。规则有一个名为fieldvalue的行,它由与sauce中的列名相关的字段组成。我想根据规则的字段名和字段值从sauce中提取数据。
我试图使用for循环,但它们花费的时间太长,并且无法从中获得正确的结果。
> sauce <- data.frame(Type = c("ketchup","mustard","mayo","lite-mayo","ketchup"), Brand = c("Heinz","Publix","Kroger","Kroger","Kroger"))
> rules <- data.frame(fieldname = c("Type","Type","Brand"),
fieldvalue = c("ketchup","lite-mayo","Kroger"),
operator = c("and","or",""),
fielname2 = c("Brand","Brand",""),
fieldvalue2 = c("Heinz","Kroger","")) 我打算索引列名,但使用了不同的数据帧sauce[,c(rules$fieldname)]
理想情况下,我希望从基于规则数据帧的sauce中获得数据。
例如: fielname: Type和fieldvalue: ketchup (并且是运算符)应该将ketchup Heinz作为输出
发布于 2019-06-02 08:56:33
apply和sprintf从rules dataframe创建条件矢量
#将and或更改为&,| rules$operator_sym <- ifelse(rules$operator=="","",ifelse(rules$operator==“”,'&','|')) conds <- apply(rules$operator==,1,function(x) if(length(xx!='')==6) sprintf("%s == ' %s‘%s == '%s'",x’‘fieldname’,x‘’fieldvalue‘,x’‘operator_sym’,x'fielname2',x'fieldvalue2') else sprintf("%s == '%s'",x‘’fieldname‘,x’‘fieldvalue’))> conds 1“类型== 'ketchup‘&品牌== 'Heinz'”“类型== 'lite-mayo’|品牌==‘克罗格’”3“品牌==‘克罗格’”
map在当前条件下遍历conds和filter sauce。使用parse_exprs将条件从字符串转换为表达式,然后使用!!! 进行计算
库(Dplyr)库(Purrr)库(Rlang)图(conds %>% set_names(),~filter(酱汁,!parse_exprs(.x) $Type == 'ketchup' & Brand == 'Heinz'类型品牌1番茄酱亨氏$Type == 'lite-mayo' | Brand == 'Kroger'类型品牌1蛋黄酱克罗格2小酱克罗格3番茄酱克罗格$Brand == 'Kroger'类型品牌1蛋黄酱克罗格2小酱克罗格3番茄酱克罗格
使用map时,输出将是一个列表,如果您希望将输出作为数据帧,则需要使用map_dfr(conds %>% set_names(), ~filter(sauce, !!!parse_exprs(.x)), .id = "Condition")
https://stackoverflow.com/questions/56402004
复制相似问题