Reputation: 15
I'm new to R and trying to create a function which I think should be fairly straight-forward but I'm stuck. I have a data frame with states and their populations for various years. I want to make 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, putting that into a function so far I have:
lotsOfPeeps<-function(dfStates){
highestPop<-max(dfStates$Jul2011)
return(highestPop)}
So, when I run lotsOfPeeps(dfStates)
right now it just returns the highest population value. How would I add to it to retrieve the state name?
Upvotes: 1
Views: 52
Reputation: 13319
A variation to make the function more flexible. This will likely be slower than which.max
.
lotsOfPeeps<-function(df, column,target_column){
highestPop<-df[df[column]==max(df[column]),target_column]
return(highestPop)
}
To get it in "column-like" format, we can wrap highestPop
in [[
as suggested by @akrun such that:
highestPop<-df[df[column]==max(df[column]),][target_column]
Testing with iris:
lotsOfPeeps(iris,"Sepal.Length","Species") # name maintained,can be better named
[1] virginica
Levels: setosa versicolor virginica
Result if highestPop is wrapped in [[
:
lotsOfPeeps(iris,"Sepal.Length","Species")
Species
132 virginica
Upvotes: 1
Reputation: 389235
Use which.max
which will return index of the highest value of population and use it to get corresponding state name. Assuming 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)
Upvotes: 1