How to display a column based on a condition that matches true for the corresponding column in data.frame in R

Below is my data.frame, it contains NA in bonus and increment.

df
name salary bonus increment(%)
AK   22200  120   2
BK   55000   34   .1
JK   12000  400   3
VK   3400   350   15
DK   5699    NA    NA

df = structure(list(name = c("AK", "BK", "JK", "VK", "DK"), salary = c(22200L, 
55000L, 12000L, 3400L, 5699L), bonus = c(120L, 34L, 400L, 350L, 
NA), 'increment(%)' = c(2, 0.1, 3, 15, NA)), .Names = c("name", 
"salary", "bonus", "increment(%)"), row.names = c(NA, -5L), class = "data.frame")

basically, I want to keep the names of those people who received the maximum salary, maximum bonus and maximum increase.

what i tried below

df[sapply(df[,2:4],function(x) which.max(x)),1]
output: [1] "BK" "JK" "VK"

But you need a reliable way that can give the same result as the above team, but also takes care of NA. Also, I'm not sure using ,1this is a good thing to display a name column.

+4
source share
2 answers

Are you looking for this?

sapply(df[,2:4], function(x) df[which(x == max(x, na.rm = TRUE)),'name'])

returns:

salary     bonus     increment(%) 
"BK"       "JK"      "VK" 
+3
source

max.col , . max.col NA, 0.

df$name[max.col(t(replace(df, is.na(df), 0))[-1, ])]

#[1] "BK" "JK" "VK"
+1

Source: https://habr.com/ru/post/1673908/


All Articles