# 如何找到最小数量的几个变量并返回列名

``````       A    B    C    D
[1,]  23   23   12   34
[2,]  12   13   11   9
[3,]  70   80   67   76
[4,]  43   23   25   40
``````

1. 每行最小数量

2. 最小值的列名

``````      A     B    C     D   min   minCol
1    23    23   12    34    12        C
2    12    13   11     9     9        D
3    70    80   67    76    67        C
4    43    23   25    40    23        B
``````

``````data <- transform(data, min=apply(data[,c(1:4)],1, min,na.rm = TRUE))
``````

``````      A     B    C     D   min
1    23    23   12    34    12
2    12    13   11     9     9
3    70    80   67    76    67
4    43    23   25    40    23
``````

``````data <- data.frame(data, minCol= apply(data, 1, function(row)
{colnames(data)[[which.min(row)]]}))
``````

``````      A     B    C     D   min   minCol
1    23    23   12    34    12        C
2    12    13   11     9     9        D
3    70    80   67    76    67        C
4    43    23   25    40    23        min
``````

``````df[c("min", "minCol")] <- t(apply(df, 1, function(x) c(min(x), names(x[which.min(x)]))))
df
#    A  B  C  D min minCol
# 1 23 23 12 34  12      C
# 2 12 13 11  9   9      D
# 3 70 80 67 76  67      C
# 4 43 23 25 40  23      B
``````

``````val <- do.call(pmin, c(df, na.rm = TRUE))
transform(df, min=val, minCol = names(df)[max.col(df == val, 'first')])
``````

``````df <- structure(list(A = c(23L, 12L, 70L, 43L), B = c(23L, 13L, 80L,
23L), C = c(12L, 11L, 67L, 25L), D = c(34L, 9L, 76L, 40L)), .Names = c("A",
"B", "C", "D"), class = "data.frame", row.names = c("1", "2",
"3", "4"))
``````

0条评论