我正在寻找每行列的最小(或最大)值的解决方案。喜欢:
# 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"
)
我尝试了 rowwise
和 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
)。
关于r - 跨多列的每行的最小(或最大值)值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50193433/