对于每一行,在条件下查找值

时间:2018-04-23 14:56:28

标签: r matrix dplyr apply

从下面的例子中,对于每一行,我试图获得" a"中的最小值。和#34; b"。

set.seed(1234)
M = matrix(sample(20,20), ncol=4)

   M
     [,1] [,2] [,3] [,4]
[1,]    3   10    7    9
[2,]   12    1    5   17
[3,]   11    4   20   16
[4,]   18    8   15   19
[5,]   14    6    2   13

colnames(M) = c("a","b","a","b")

所以,这就是我所希望的

       "a"  "b"
[1,]    3    9
[2,]    5    1
[3,]   11    4
[4,]   15    8
[5,]    2    6

1 个答案:

答案 0 :(得分:4)

以下是将ggplot(toy_df, aes(x = ID, y = prop, fill = group, alpha=toy_df$ID != 2)) + geom_bar(stat = "identity") + scale_alpha_manual(values=c(1, 0.7)) + guides(alpha=F) (转换为data.frame)按列名称拆分并获取每行data.frame的一个选项

pmin

如果我们需要最小值的列号,请使用sapply(split.default(as.data.frame(M), colnames(M)), function(x) do.call(pmin, x)) # a b #[1,] 3 9 #[2,] 5 1 #[3,] 11 4 #[4,] 15 8 #[5,] 2 6

max.col