[英]How can I calculate the mean and standard deviation of a column in a data frame using the dplyr package?
[英]How can I calculate the sum of the column wise differences using dplyr
尽管定期使用 R 和 dplyr,但我遇到了无法计算所有列之间绝对差之和的问题:
sum_diff=ABS(AB)+ABS(BC)+ABS(CD)...
一种 | 乙 | C | 丁 | 和差 |
---|---|---|---|---|
1个 | 2个 | 3个 | 4个 | 3个 |
2个 | 1个 | 3个 | 4个 | 4个 |
1个 | 2个 | 1个 | 1个 | 2个 |
4个 | 1个 | 2个 | 1个 | 5个 |
我知道我可以在所有列上使用 for 循环进行迭代,但考虑到我的数据框的大小,我更喜欢更优雅、更快速的解决方案。
有什么帮助吗?
谢谢
我们可以删除第一列和最后一列,获取差异,并对base R
R 中的abs
使用rowSums
。 与 package 解决方案相比,这可能非常有效
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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.