r - 求R中同名列之间的最大差异

标签 r max multiple-columns string-matching minima

我在 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/

相关文章:

html - 等高列仅适用于 Chrome

R Shiny 文件 : Warning: Error in [: object of type 'closure' is not subsettable [No stack trace available]

php - PHP max_execution_time 的确切含义

algorithm - 容量为 y、x*y 项目的 x 箱子,最大化总分,其中每个(项目,箱子)对都有一个相关联的分数

css - 为什么我的媒体查询不起作用?

html - 在不是全宽的可变大小容器内居中?

R:当列数为素数时分割数据框

r - 使用ggplot2在每个因子内对条形进行排序

r - 来自 R 代码块的动态 RMarkdown 标题

返回 R 中相关列中向量和字符串的最高值