r - 跨多列的每行的最小(或最大值)值

标签 r dplyr

我正在寻找每行列的最小(或最大)值的解决方案。喜欢:

# my data.frame is df:

library(tibble)
df <- tribble(
~name, ~type_1, ~type_2, ~type_3,
"a",   1,   5, 2,
"b",   2,   2, 6,
"c",   3,   8, 2
)

# and output should be result_df:

result_df <- tribble(
~name, ~type_1, ~type_2, ~type_3, ~min_val, ~min_col,
"a",   1,          5,     2,          1, "type_1",
"b",   8,          2,     6,          2, "type_2",
"c",   3,          8,     0,          0 ,"type_3"
)

我尝试了 rowwisepmax 函数,但没有用。我可以使用收集和分组,但我想知道是否有列/行解决方案。

这种方法对于均值、中值函数也很有用。

感谢您的帮助。

最佳答案

基本 R 方法有问题吗?

# find the columns in question
mask <- colnames(df)[startsWith(colnames(df), 'type_')]

# apply row-wise and transpose afterwards
df[c('min_val', 'min_col')] <- t(apply(df[mask], 1, function(x) {
  m <- which.min(x)
  (y <- c(x[m], mask[m]))
}))

这产生

# A tibble: 3 x 6
  name  type_1 type_2 type_3 min_val min_col
  <chr>  <dbl>  <dbl>  <dbl> <chr>   <chr>  
1 a         1.     5.     2. 1       type_1 
2 b         2.     2.     6. 2       type_1 
3 c         3.     8.     2. 2       type_3 

请注意,which.min() 取第一个找到的匹配项(第二行有两个 2)。

关于r - 跨多列的每行的最小(或最大值)值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50193433/

相关文章:

r - 使用列名 (R) 更改数据表中的单元格值?

使用 dplyr 管道替换对角线元素

r - 按 R 中另一个分类变量的比例对一个变量进行排序

r - 当每组 n 不同时过滤 n 行分组数据框

r - 在矩阵中使用 vctr

r - 在 Shiny 中使用 data.table 卡住标题和第一列

r - 在 Shiny 的 DataTable 实现中控制数字格式

r - 使用 lubridate 和 dplyr 将多列转换为日期

R:将月份添加到日期的有效方法?

r - Shiny 的 selectizeInput : Read current text