parvij
parvij

Reputation: 1390

How to find minimum column name by condition on values in R

I need minimum column name between column that has positive value.

set.seed(123)
dts=data.frame(matrix(rnorm(30), nrow = 10))
colnames(dts)=c('2','3','4')

for example for bellow data set last column is answer, how could I build it?

    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

Upvotes: 1

Views: 187

Answers (3)

alistaire
alistaire

Reputation: 43364

If you build a matrix with col values where dts is positive and NA everywhere else, you can apply which.min rowwise:

# 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

Upvotes: 1

akrun
akrun

Reputation: 887941

We can also try with max.col

 max.col(-replace(dts, dts <0, 999), "first")
 #[1] 2 2 2 1 1 1 1 3 2 3

If we need the minimum column names

 max.col(-replace(col(dts), dts <0, 999), "first")
 #[1] 2 2 1 1 1 1 1 3 2 3

Upvotes: 3

Sotos
Sotos

Reputation: 51592

apply(dts, 1, function(i) names(dts[i > 0])[1])
#[1] "2" "2" "1" "1" "1" "1" "1" "3" "2" "3"

Upvotes: 3

Related Questions