How do I use an apply function in R to find the maximum of a variable for subgroups

 salary <- data.frame(name=c("Kay","Dave","Jon","Jenny","Jim","Eve","Ed"),
 salary=c(60000, 100000, 50000, 80000, 30000, 40000, 20000),
 gender=factor(c("F","M","M","F","M","F","M")))

I am able to filter a female data frame with

femaleFiltered <- salary[ which(salary$gender=='F'), ]

and I am trying to use

getMaxSal1 <- function(x) {
    x[which.max(x$salary),]
}

apply(femaleFiltered,2,getMaxSal1)

but get error "Error in x$salary: $ operator is invalid for atomic vectors"



Read more here: https://stackoverflow.com/questions/67942978/how-do-i-use-an-apply-function-in-r-to-find-the-maximum-of-a-variable-for-subgro

Content Attribution

This content was originally published by Rohit Goswami at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: