如何使用 dplyr 计算列差异的总和
How can I calculate the sum of the column wise differences using dplyr
尽管经常使用 R 和 dplyr,但我遇到了无法计算所有列之间绝对差之和的问题:
sum_diff=ABS(A-B)+ABS(B-C)+ABS(C-D)...
A
B
C
D
sum_diff
1
2
3
4
3
2
1
3
4
4
1
2
1
1
2
4
1
2
1
5
我知道我可以在所有列上使用 for 循环进行迭代,但考虑到我的数据框的大小,我更喜欢更优雅、更快速的解决方案。
有什么帮助吗?
谢谢
我们可能会删除第一列和最后一列,得到差异,然后在 base R
中的 abs
olute 值上使用 rowSums
。与打包解决方案相比,这可能非常有效
df1$sum_diff <- rowSums(abs(df1[-ncol(df1)] - df1[-1]))
-输出
> df1
A B C D sum_diff
1 1 2 3 4 3
2 2 1 3 4 4
3 1 2 1 1 2
4 4 1 2 1 5
或者另一个选项是 rowDiffs
来自 matrixStats
library(matrixStats)
rowSums(abs(rowDiffs(as.matrix(df1))))
[1] 3 4 2 5
数据
df1 <- structure(list(A = c(1L, 2L, 1L, 4L), B = c(2L, 1L, 2L, 1L),
C = c(3L, 3L, 1L, 2L), D = c(4L, 4L, 1L, 1L)), row.names = c(NA,
-4L), class = "data.frame")
来自 akrun 的数据(非常感谢)!
这个想法很复杂,我想生成一个组合列表,我用 combn
试了一下,但后来我得到了所有可能的组合。所以我手工创建了。
有了这个组合,我们就可以使用 purrr
s map_dfc
然后做一些数据整理:
library(tidyverse)
combinations <-list(c("A", "B"), c("B", "C"), c("C","D"))
purrr::map_dfc(combinations, ~{df <- tibble(a=data[[.[[1]]]]-data[[.[[2]]]])
names(df) <- paste0(.[[1]],"_v_",.[[2]])
df}) %>%
transmute(sum_diff = rowSums(abs(.))) %>%
bind_cols(data)
sum_diff A B C D
<dbl> <int> <int> <int> <int>
1 3 1 2 3 4
2 4 2 1 3 4
3 2 1 2 1 1
4 5 4 1 2 1
数据:
data <- structure(list(A = c(1L, 2L, 1L, 4L), B = c(2L, 1L, 2L, 1L),
C = c(3L, 3L, 1L, 2L), D = c(4L, 4L, 1L, 1L)), row.names = c(NA,
-4L), class = "data.frame")
尽管经常使用 R 和 dplyr,但我遇到了无法计算所有列之间绝对差之和的问题:
sum_diff=ABS(A-B)+ABS(B-C)+ABS(C-D)...
A | B | C | D | sum_diff |
---|---|---|---|---|
1 | 2 | 3 | 4 | 3 |
2 | 1 | 3 | 4 | 4 |
1 | 2 | 1 | 1 | 2 |
4 | 1 | 2 | 1 | 5 |
我知道我可以在所有列上使用 for 循环进行迭代,但考虑到我的数据框的大小,我更喜欢更优雅、更快速的解决方案。
有什么帮助吗?
谢谢
我们可能会删除第一列和最后一列,得到差异,然后在 base R
中的 abs
olute 值上使用 rowSums
。与打包解决方案相比,这可能非常有效
df1$sum_diff <- rowSums(abs(df1[-ncol(df1)] - df1[-1]))
-输出
> df1
A B C D sum_diff
1 1 2 3 4 3
2 2 1 3 4 4
3 1 2 1 1 2
4 4 1 2 1 5
或者另一个选项是 rowDiffs
来自 matrixStats
library(matrixStats)
rowSums(abs(rowDiffs(as.matrix(df1))))
[1] 3 4 2 5
数据
df1 <- structure(list(A = c(1L, 2L, 1L, 4L), B = c(2L, 1L, 2L, 1L),
C = c(3L, 3L, 1L, 2L), D = c(4L, 4L, 1L, 1L)), row.names = c(NA,
-4L), class = "data.frame")
来自 akrun 的数据(非常感谢)!
这个想法很复杂,我想生成一个组合列表,我用 combn
试了一下,但后来我得到了所有可能的组合。所以我手工创建了。
有了这个组合,我们就可以使用 purrr
s map_dfc
然后做一些数据整理:
library(tidyverse)
combinations <-list(c("A", "B"), c("B", "C"), c("C","D"))
purrr::map_dfc(combinations, ~{df <- tibble(a=data[[.[[1]]]]-data[[.[[2]]]])
names(df) <- paste0(.[[1]],"_v_",.[[2]])
df}) %>%
transmute(sum_diff = rowSums(abs(.))) %>%
bind_cols(data)
sum_diff A B C D
<dbl> <int> <int> <int> <int>
1 3 1 2 3 4
2 4 2 1 3 4
3 2 1 2 1 1
4 5 4 1 2 1
数据:
data <- structure(list(A = c(1L, 2L, 1L, 4L), B = c(2L, 1L, 2L, 1L),
C = c(3L, 3L, 1L, 2L), D = c(4L, 4L, 1L, 1L)), row.names = c(NA,
-4L), class = "data.frame")