Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/279.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将mapply转换为pmap或类似文件,以便在R中对数据进行分组_R_Dplyr - Fatal编程技术网

如何将mapply转换为pmap或类似文件,以便在R中对数据进行分组

如何将mapply转换为pmap或类似文件,以便在R中对数据进行分组,r,dplyr,R,Dplyr,我有一个mapply函数,它运行一个求和表达式,这样每一行的求和都从同一个数字开始。ie第1行:从第1行开始求和,第2行:从第2行开始求和,等等。这很好,但是我现在需要能够在分组数据上运行它,我在运行它时遇到了一些问题。我相信pmap与dplyr中的mapply类似,因此我尝试将其用于分组数据 数据如下所示: df <- tibble(NCP = c(96.05655668, 16.94332276, 19.8844913, 17.74200903, 17.6135507,

我有一个mapply函数,它运行一个求和表达式,这样每一行的求和都从同一个数字开始。ie第1行:从第1行开始求和,第2行:从第2行开始求和,等等。这很好,但是我现在需要能够在分组数据上运行它,我在运行它时遇到了一些问题。我相信
pmap
dplyr
中的
mapply
类似,因此我尝试将其用于分组数据

数据如下所示:

df <- tibble(NCP = c(96.05655668, 16.94332276, 19.8844913, 17.74200903, 17.6135507, 
                     15.1, 12.2,  13.1, 3.3, 47.8, 12.3,1.8),
             time_bin =  c(100,200,300,400,500, 100, 200, 300, 400, 500, 600, 700),
             site = site <- c("A","A","A","A","A","B","B","B","B","B","B","B"),
             output = c(14.01221047, 6.51265852, 5.399067538, 3.743397662, 2.02022025, 
                         123.1815734, 106.8239387, 92.50710604, 75.85374217, 71.30922055,
                        23.02892565, 3.151210501))

df仅使用
pmap\u dbl
翻译您的尝试:

library(dplyr)
library(purrr)

df%>%
  group_by(site) %>% 
  mutate(output = pmap_dbl(list(seq_len(n()), exp(-0.0008 * time_bin), 
                                exp(-0.0008 * c(0, time_bin[-n()]))), 
                  function(i, tb, tblag) sum(NCP[i:n()]/tb - NCP[i:n()]/tblag)))
 df1 <- df%>%
  group_by(site) %>% 
  summarise(nrow = n())

df <- right_join(df1, df)

df <- df %>% group_by(site) %>% 
mutate(out = pmap(.,  function(i, tb, tblag){sum(df$NCP[i:max(nrow)]/tb - df$NCP[i:max(nrow)]/tblag),
                  seq_len(max(nrow)), exp(-0.0008 * df$time_bin), exp(-0.0008 * c(0, df$time_bin[-max(nrow)])))}
library(dplyr)
library(purrr)

df%>%
  group_by(site) %>% 
  mutate(output = pmap_dbl(list(seq_len(n()), exp(-0.0008 * time_bin), 
                                exp(-0.0008 * c(0, time_bin[-n()]))), 
                  function(i, tb, tblag) sum(NCP[i:n()]/tb - NCP[i:n()]/tblag)))