Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (5.3k points)

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 store the name of those persons who have got a max salary, max bonus and max increment.

what I have tried is below

df[sapply(df[,2:4],function(x) which.max(x)),1]

output: [1] "BK" "JK" "VK"

But need a robust way which can give the same output as above command but takes care of NA as well. Also, I am not sure using, 1 is a good thing to display the name column.

1 Answer

0 votes
by

You can use the na.rm argument to take of NA values and add the column name to display the “name” column as follows:

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")

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

      salary        bonus increment(%) 

        "BK"         "JK"         "VK" 

Browse Categories

...