代码之家  ›  专栏  ›  技术社区  ›  Sylvia Rodriguez

计算R中各列之间的差异

  •  0
  • Sylvia Rodriguez  · 技术社区  · 2 年前

    我有这个 data.frame :

     df <- data.frame(name = c('sample1', 'sample2'),
          a = c(1.12, 3.18),
          b = c(2.23, 6.29),
          c = c(3.62, 1.72),
          d = c(11.56, 6.22),
          e = c(4.11, 19.38))
    

    我可以使用以下方法计算各列的平均值:

     library(dplyr)
     df_mean <- df %>% summarise(across(where(is.numeric), ~mean(.x, na.rm=TRUE)))
    

    但我怎么能得到类似的 df 用差值而不是均值?我试过这个,但不起作用:

     df_difference <- df %>% summarise(across(where(is.numeric), ~.y-.x))
    

    预期结果为:

     df_difference <- data.frame(a=2.06, b=4.06, b=-1.9, c=-5.34, d=15.27)
    
    1 回复  |  直到 2 年前
        1
  •  1
  •   ThomasIsCoding    2 年前

    尝试 diff

    > df %>% summarise(across(where(is.numeric), diff))
         a    b    c     d     e
    1 2.06 4.06 -1.9 -5.34 15.27
    
        2
  •  0
  •   linkonabe    2 年前

    此解决方案参考@Friede解释。

    df <- df %>%
      summarise(across(where(is.numeric), ~.[-1] - .[1])) 
    
      a     b     c     d      e
    1  2.06  4.06 -1.90 -5.34 15.27
    

    这个想法基本上是从第二行减去第一行。[-1]表示第二行,[1]表示每列中的第一行