Explore Courses Blog Tutorials Interview Questions
0 votes
in R Programming by (50.2k points)
edited by

In R I am having a data frame with states and their populations for various years. I want to build a function which finds the highest population in a given year and returns the corresponding state name. I know how to retrieve the max population, but I don't know how to use that to look up the corresponding state name. Here's my code to find the max population:


Now, I am having the following:




So, when I executed the lotsOfPeeps(dfStates) function right now it will only returns the highest population. How would I continue to it to reclaim the state name?

1 Answer

0 votes
by (108k points)

You can use the which.max() which will return index of the highest value of population and use it to get corresponding state name. I am assuming that the column with state name is called StateName, you can do:


   hihest_pop_state <- dfStates$StateName[which.max(dfStates$Jul2011)]




If you want to know more about R then do check out the R programming course

Browse Categories