计算 R 中各列的差异

问题描述 投票:0回答:1

我有这个

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)
r dplyr multiple-columns
1个回答
0
投票

尝试

diff

> df %>% summarise(across(where(is.numeric), diff))
     a    b    c     d     e
1 2.06 4.06 -1.9 -5.34 15.27
© www.soinside.com 2019 - 2024. All rights reserved.