我在 R 中有下表。我有 2 个 A 列、3 个 B 列和 1 个 C 列。我需要计算任何同名列之间可能的最大差异,并将列名称作为输出返回。
对于第 1 行
- A 之间的最大差异为 2
- B 之间的最大差异为 4
- 我需要输出为 B
对于第 2 行
- A 之间的最大差异为 3
- B 之间的最大差异为 2
- 我需要输出为 A
| A | A | B | B | B | C |
| 2 | 4 |5 |2 |1 |0 |
| -3 |0 |2 |3 |4 |2 |
最佳答案
首先,使用非唯一的列名有点危险(在某些情况下不允许),所以我做的第一件事是使用 base::make.unique() 唯一化名称
。从那里,我使用了 tidyr::pivot_longer() ,以便可以更轻松地访问列名称中包含的分组信息。在这里,我在 names_pattern
中使用正则表达式来丢弃列名称的差异部分,以便它们再次相同。然后我们使用 dplyr::group_by()
和 dplyr::summarize()
来获得每个 id
和 中的最大差异grp
对应于原始数据中的行和类似列。最后,我们使用 dplyr::slice_max() 来仅返回每组的最大差异。
library(tidyverse)
d <- structure(list(A = c(2L, -3L), A = c(4L, 0L), B = c(5L, 2L), B = 2:3, B = c(1L, 4L), C = c(0L, 2L)), row.names = c(NA, -2L), class = "data.frame")
# give unique names
names(d) <- make.unique(names(d), sep = "_")
d %>%
mutate(id = row_number()) %>%
pivot_longer(-id, names_to = "grp", names_pattern = "([A-Z])*") %>%
group_by(id, grp) %>%
summarise(max_diff = max(value) - min(value)) %>%
slice_max(order_by = max_diff, n = 1, with_ties = F)
#> `summarise()` has grouped output by 'id'. You can override using the `.groups` argument.
#> # A tibble: 2 x 3
#> # Groups: id [2]
#> id grp max_diff
#> <int> <chr> <int>
#> 1 1 B 4
#> 2 2 A 3
由 reprex package 于 2022 年 2 月 14 日创建(v2.0.1)
关于r - 求R中同名列之间的最大差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71106399/