【问题标题】:How to use mutate iteratively over multiple rows in r如何在 r 中的多行上迭代地使用 mutate
【发布时间】:2018-09-07 14:49:11
【问题描述】:

我正在尝试计算每组个体的所有可能数据对之间的 ht 百分比差异,以及 ht 度量之间的时间差。这是我的数据:

hc1<- data.frame(id= c(1,1,1,2,2,2,3,3),
                  testoccasion= c(1,2,3,1,2,3,1,2),
                  ht= c(0.2,0.1,0.8,0.9,1.0,0.5,0.4,0.8),
                  time= c(5,4,8,5,6,5,2,1))

这是我的代码。

library(dplyr)
a<-hc1 %>% 
   group_by(id) %>% 
   arrange(id,testoccasion) %>% 
   mutate(fd = (ht-lag(ht))/lag(ht)*100) %>% 
   mutate(t = time-lag(time))
b<-hc1 %>% 
   group_by(id) %>% 
   arrange(id,testoccasion) %>% 
   mutate(fd = (ht-lag(ht,2))/lag(ht,2)*100) %>% 
   mutate(t = time-lag(time,2))
c<-hc1 %>% 
   group_by(id) %>% 
   arrange(id,testoccasion) %>% 
   mutate(fd = (ht-lag(ht,3))/lag(ht,3)*100) %>% 
   mutate(t = time-lag(time,3))

diff<-rbind(a,b,c)
diff<-na.omit(diff)

我很好奇如何使这段代码更短。我希望能够找到所有可能的 ht 对之间的差异,对于所有测试场合,其中测试场合的数量在各个 id 之间有所不同。如果我不必像这样迭代地做它会很棒,因为这是我拥有的一个巨大的数据集。谢谢!

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    我们可以使用map来循环lag中使用的n

    library(tidyverse)
    map_df(1:3, ~ 
                hc1 %>%
                    group_by(id) %>% 
                    arrange(id, testoccasion) %>% 
                    mutate(fd = (ht -lag(ht, .x))/lag(ht, .x) * 100,
                    t = time -lag(time, .x)))  %>%
      na.omit
    # A tibble: 7 x 6
    # Groups:   id [3]
    #     id testoccasion    ht  time     fd     t
    #  <dbl>        <dbl> <dbl> <dbl>  <dbl> <dbl>
    #1     1            2   0.1     4  -50      -1
    #2     1            3   0.8     8  700       4
    #3     2            2   1       6   11.1     1
    #4     2            3   0.5     5  -50      -1
    #5     3            2   0.8     1  100      -1
    #6     1            3   0.8     8  300.      3
    #7     2            3   0.5     5  -44.4     0
    

    【讨论】:

    • 啊,非常感谢!!只是好奇,代码开头的1:3是什么?
    • @lok​​es 那是在lag 中创建ac 时使用的n。默认情况下,n=1 所以在你的代码中没有指定
    猜你喜欢
    • 1970-01-01
    • 2014-02-12
    • 2021-05-11
    • 2021-06-14
    • 2021-07-03
    • 2016-08-12
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    相关资源
    最近更新 更多