我需要具有正值的列之间的最小列名。
set.seed(123)
dts=data.frame(matrix(rnorm(30), nrow = 10))
colnames(dts)=c('2','3','4')
例如对于波纹管数据集最后一列是答案,我该如何构建它?
2 3 4 answer
1 -0.56047565 1.2240818 -1.0678237 3
2 -0.23017749 0.3598138 -0.2179749 3
3 1.55870831 0.4007715 -1.0260044 2
4 0.07050839 0.1106827 -0.7288912 2
5 0.12928774 -0.5558411 -0.6250393 2
6 1.71506499 1.7869131 -1.6866933 2
7 0.46091621 0.4978505 0.8377870 2
8 -1.26506123 -1.9666172 0.1533731 4
9 -0.68685285 0.7013559 -1.1381369 3
10 -0.44566197 -0.4727914 1.2538149 4
答案 0 :(得分:3)
apply(dts, 1, function(i) names(dts[i > 0])[1])
#[1] "2" "2" "1" "1" "1" "1" "1" "3" "2" "3"
答案 1 :(得分:3)
我们也可以尝试max.col
max.col(-replace(dts, dts <0, 999), "first")
#[1] 2 2 2 1 1 1 1 3 2 3
如果我们需要最小列名
max.col(-replace(col(dts), dts <0, 999), "first")
#[1] 2 2 1 1 1 1 1 3 2 3
答案 2 :(得分:1)
如果您构建一个col
值的矩阵,其中dts
为正,而其他地方为NA
,则可以apply
which.min
逐行:
# the matrix to apply over
ifelse(dts > 0, col(dts), NA)
## 1 2 3
## [1,] NA 2 NA
## [2,] NA 2 NA
## [3,] 1 2 NA
## [4,] 1 2 NA
## [5,] 1 NA NA
## [6,] 1 2 NA
## [7,] 1 2 3
## [8,] NA NA 3
## [9,] NA 2 NA
## [10,] NA NA 3
# apply which.min to each row
apply(ifelse(dts > 0, col(dts), NA), 1, which.min)
## [1] 2 2 1 1 1 1 1 3 2 3