如何在R中进行动态数据框索引

时间:2019-05-31 21:40:41

标签: r dataframe indexing dynamic

我有两个数据框;酱和规则。规则中有一个名为fieldname的列,它由调味汁中的列名组成。规则有一个名为fieldvalue的行,其中包含与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)]

理想情况下,我希望基于规则数据框从酱汁中获取数据。

例如:fielname:类型和字段值:ketchup(并且是操作员)应导致ketchup Heinz作为输出

1 个答案:

答案 0 :(得分:0)

  1. 从规则数据框中使用<p>float创建条件向量

    ESC $ n1 n2 or X'1B;24;n1;n2'
    Where:
    • n1 is the high-order byte of the dot offset from the beginning of the print line.
    • n2 is the low-order byte of the dot offset from the beginning of the print line.
    Default:
    n1 = 0, n2 = 0```
    
  2. 使用apply使用当前条件在sprintf#Change and, or to &, | rules$operator_sym <- ifelse(rules$operator=="","",ifelse(rules$operator=="and",'&','|')) conds <- apply(rules, 1, function(x) if(length(x[x!=''])==6) sprintf("%s == '%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] "Type == 'ketchup' & Brand == 'Heinz'" "Type == 'lite-mayo' | Brand == 'Kroger'" [3] "Brand == 'Kroger'" sauce 中循环。使用map将条件从字符串转换为R表达式,然后使用conds

    进行评估
    filter

如果您希望将输出作为数据框使用parse_exprs,则使用!!!将是一个列表{p}