【问题标题】:Apply function that return data.frame/tibble on vector/data.frame column and bind results应用在 vector/data.frame 列上返回 data.frame/tibble 的函数并绑定结果
【发布时间】:2019-07-16 12:47:57
【问题描述】:

我有一个从数据库中获取一些数据的函数。它接受一个参数并返回一个 data.frame。我想使用这些参数的输入向量并将它们传递给 map 或类似的函数,该函数接受每个元素并返回 db 结果。结果可能在行中有所不同,但列始终相同。我如何在没有循环和行绑定的情况下进行? (对于我在..)

我尝试了以下路线:

myfuncSingleRow<-function(nbr){ 
data.frame(a=nbr,b=nbr^2,c=nbr^3)}

myfuncMultipleRow<-function(nbr){ 
    data.frame(a=rep(nbr,3),b=rep(nbr^2,3),c=rep(nbr^3,3))}

a<-data.frame(count=c(1,2,3))

myfuncSingleRow(2)
myfuncMultipleRow(2)


a %>% select(count) %>% map_dfr(.f=myfuncSingleRow) #output as expected    
a %>% select(count) %>% map_dfr(.f=myfuncMultipleRow) #output not as expected

现在这也不能按预期工作。示例 myFuncMultipleRow,我希望前 3 行相等,接下来的 3 行相等,最后 3 行相同。使用 myFuncMultipleRow 的示例:

得到

  a b  c
1 1 1  1
2 2 4  8
3 3 9 27
4 1 1  1
5 2 4  8
6 3 9 27
7 1 1  1
8 2 4  8
9 3 9 27

想要:

  a b  c
1 1 1  1
2 1 1  1
3 1 1  1
4 2 4  8
5 2 4  8
6 2 4  8
7 3 9 27
8 3 9 27
9 3 9 27

像往常一样,我可能没有正确使用这些功能,但有点卡在这里不想解决旧循环和 rbind,这可能会成为性能瓶颈。有接盘侠吗?

编辑:正如在“rep”中指出的“每个”参数确实解决了这个问题,但没有解决主要问题。如果 map 确实为每个元素迭代并调用函数,那么对函数“rep”使用参数“each”和“times”应该会产生相同的结果。传递给 map 的函数不是向量化的,而是假定一个长度为 1 的参数。 需要做的解决方案:

res<-data.frame()
for(i in a) res<-rbind(res,myfuncMultipleRow(i))

【问题讨论】:

    标签: r dplyr tidyverse purrr


    【解决方案1】:

    因此,在查看了最新的 purrr 0.3.0(在旧版本上)之后,map_depth 指向了正确的方向。

    a %>% select(count)%>% map_depth(.depth=2,.f=myfuncMultipleRow) %>%  map_dfr(.f=bind_rows)
    

    删除 map_depth() 、 bind_rows() 并改为嵌套:

    a %>% select(count)%>% map_dfr(~map_dfr(.,myfuncMultipleRow))
    a %>% select(count)%>% map_dfr(.f=function(x) map_dfr(x,.f=myfuncMultipleRow))
    

    【讨论】:

      猜你喜欢
      • 2018-07-17
      • 2016-05-09
      • 1970-01-01
      • 1970-01-01
      • 2011-12-28
      • 1970-01-01
      • 1970-01-01
      • 2011-10-19
      相关资源
      最近更新 更多