Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
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:

max(dfStates$Jul2011)

Now, I am having the following:

lotsOfPeeps<-function(dfStates){

  highestPop<-max(dfStates$Jul2011)

  return(highestPop)}

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 (107k 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:

lotsOfPeeps<-function(dfStates){

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

   return(hihest_pop_state)

}

lotsOfPeeps(dfStates)

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

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...