【问题标题】:Apply function to each row for each group in dplyr group by将函数应用于 dplyr 组中每个组的每一行
【发布时间】:2018-06-06 01:38:11
【问题描述】:

我有一个数据框,其中包含要应用的函数,让 f1 和 f2 表示这些函数,它们以 dbhht 作为参数。

spcd   region   function
122    'OR_W'   f1 
141    'OR_W'   f2

我也有一个看起来像的数据框

spcd   region   dbh   ht
122    'OR_W'   12    101
122    'OR_W'   13    141
122    'OR_W'   15    122
141    'OR_W'   12    101

我想将存储在第一个数据帧中的函数应用到第二个数据帧中的行以产生类似的结果

spcd   region   dbh   ht   output
122    'OR_W'   12    101  <output of f1>
122    'OR_W'   13    141  <output of f1>
122    'OR_W'   15    122  <output of f1>
141    'OR_W'   12    101  <output of f2>

其中&lt;output of f1&gt; 是第一个函数的输出,输入为 dbh 和 ht。

我认为 dplyr 的 group_by 对此很有用,方法是对第二个数据帧中的 spcd 和区域进行分组,然后对该组中的每一行应用正确的函数。

有没有办法将函数逐行应用于 dplyr group_by 对象中的组?

【问题讨论】:

  • 你介意使用base R吗?你也可以举一个可重现的例子吗?
  • Map(function(f,x)apply(x,1,f),c(data1$function),split(data2,spcd))。当且仅当data1$function 可以尝试使用is.function(data[1,3]) 来查看它们是否存储为函数
  • 加入并使用purrr::invoke_map 变体,但您需要to make the example reproducible 才能获得正确答案。

标签: r dplyr


【解决方案1】:

这是一个基本的解决方案;

 Map(apply,split(data1[-1],data1$d),1,c(data2$fun))) 

 data1["output"]=c(mapply(apply,split(data1[-1],data1$d),1,c(data2$fun)))
 data1
    d Girth Height Volume output
 1  1   8.3     70   10.3   88.6
 2  1   8.6     65   10.3   83.9
 3  1   8.8     63   10.2   82.0
 4  1  10.5     72   16.4   98.9
 5  1  10.7     81   18.8  110.5
 6  2  10.8     83   19.7   83.0
 7  2  11.0     66   15.6   66.0
 8  2  11.0     75   18.2   75.0
 9  2  11.1     80   22.6   80.0
 10 2  11.2     75   19.9   75.0

使用的数据:

 data1=structure(list(d = c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L), 
                 Girth = c(8.3, 8.6, 8.8, 10.5, 10.7, 10.8, 11, 11, 11.1, 
                           11.2), Height = c(70, 65, 63, 72, 81, 83, 66, 75, 80, 75), 
                 Volume = c(10.3, 10.3, 10.2, 16.4, 18.8, 19.7, 15.6, 18.2, 
                            22.6, 19.9)), .Names = c("d", "Girth", "Height", "Volume"
                            ), row.names = c(NA, 10L), class = "data.frame")
 data2=structure(list(X1.2 = 1:2, fun = c("sum", "max")), .Names = c("X1.2", 
                                                                "fun"), row.names = c(NA, -2L), class = "data.frame")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-16
    • 1970-01-01
    • 2023-04-04
    • 2023-01-10
    • 2015-05-16
    相关资源
    最近更新 更多