多列中每行的最小值(或最大值)

2023-12-10

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

# 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"
)

I tried rowwise and pmax功能但没有起作用。我可以使用收集和分组,但我想知道是否存在按列/按行的解决方案。

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

感谢您的帮助。


是不是底座有问题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在第二行)。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

多列中每行的最小值(或最大值) 的相关文章

随机推荐