2

I am trying to get the results from 3 columns and adding the result in the result column under the same row
My data

╔════════════════════════════════════════════════╗
║ No    CART    RF    XG     Result              ║
╠════════════════════════════════════════════════╣
║ 1      Yes    No    No        No               ║
║ 2      Yes    Yes   No        Yes              ║
╚════════════════════════════════════════════════╝

How do I get the Result column by looking at CART, RF and XG?

Hal
  • 372
  • 4
  • 13

2 Answers2

2

Disclaimer(Self promotion): Using manymodelr(For a more uptodate version, use the developer version), we can get the mode rowwise:

 df$Res<-apply(df[,-4],1,manymodelr::get_mode)
 df
  No CART  RF XG Result Res
1  1  Yes  No No     No  No
2  2  Yes Yes No    Yes Yes

Data:

df <-structure(list(No = 1:2, CART = structure(c(1L, 1L), .Label = "Yes", class = "factor"), 
    RF = structure(1:2, .Label = c("No", "Yes"), class = "factor"), 
    XG = structure(c(1L, 1L), .Label = "No", class = "factor"), 
    Result = structure(1:2, .Label = c("No", "Yes"), class = "factor")), class = "data.frame", row.names = c(NA, 
-2L))
NelsonGon
  • 13,015
  • 7
  • 27
  • 57
1

Taking the mode function from here,

Mode <- function(x) {
   ux <- unique(x)
   ux[which.max(tabulate(match(x, ux)))]
}

we can apply it row-wise using apply

df$Result <- apply(df[-1], 1, Mode)
df

#  No CART  RF XG Result
#1  1  Yes  No No     No
#2  2  Yes Yes No    Yes
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213