if else statement

I am trying to create a new column based on my variable that will give me the column name with the max value being V1,V2, or V3
my coding was:
colnames(exp1)[apply(exp1,1,which.max)]

id  V1 V2 V3
1     2  7  9
2     8  3  6
3     1  5  4

Is this what you mean?

library(dplyr)

sample_df <- data.frame(
          id = c(1, 2, 3),
          V1 = c(2, 8, 1),
          V2 = c(7, 3, 5),
          V3 = c(9, 6, 4)
)

sample_df %>% 
    rowwise() %>% 
    mutate(max = names(sample_df)[2:4][which.max(c(V1, V2, V3))])
#> Source: local data frame [3 x 5]
#> Groups: <by row>
#> 
#> # A tibble: 3 x 5
#>      id    V1    V2    V3 max  
#>   <dbl> <dbl> <dbl> <dbl> <chr>
#> 1     1     2     7     9 V3   
#> 2     2     8     3     6 V1   
#> 3     3     1     5     4 V2

Created on 2020-01-27 by the reprex package (v0.3.0.9000)

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.