Reputation: 95
I need to write a function to return the name of the senators for a given state. I'm new to R and am having trouble writing the actual function. Given this sample data:
df <- data.frame(lastname=c("Jones","Smith","Collins","Graham","Smith","White"),
firstname=c("William","John","Leslie","Daniel","Marc","Jill"),
state=c("OH","MT","WI","OH","IN","OH"))
lastname firstname state
1 Jones William OH
2 Smith John MT
3 Collins Leslie WI
4 Graham Daniel OH
5 Smith Marc IN
6 White Jill OH
senatorbystate <- function(state)
{
for(i in 1:dim(df)[1])
{
if(df$state[i] == state)
{
x[i] <- c(df$firstname[i] && df$lastname[i])
}
return(x)
}
}
senatorbystate("OH")
The output that I am looking for is a vector of the senators for the specified state:
> William Jones, Daniel Graham, Jill White
Upvotes: 2
Views: 231
Reputation: 1057
A slightly smaller version,
senatorbystate <- function(state) with(df[df$state==state, ],
paste(firstname, lastname, collapse=", "))
Remove collapse
if you want a character array as output
Upvotes: 2
Reputation: 521239
I refactored your senatorbystate()
function to split your data frame df
on the input state, which yields a list of data frames, each one corrsponding to a certain state. Then I aggregate the first and last name columns for the input state and return a vector of names.
# convert names columns to character in case they are factors
df$lastname <- as.character(df$lastname)
df$firstname <- as.character(df$firstname)
senatorbystate <- function(state, data) {
data.split <- split(data, data$state)
result <- paste(data.split[[state]]$firstname,
data.split[[state]]$lastname,
sep=" ")
return(result)
}
Usage:
> output <- senatorbystate("OH", df)
[1] "William Jones" "Daniel Graham" "Jill White"
> output[2]
[1] "Daniel Graham"
Upvotes: 2
Reputation:
A variation to Tim Biegeleisen answer:
senatorbystate <- function(data, state){
out <- split(data, data$state %in% state)[["TRUE"]]
res <- with(out, paste(firstname, lastname, collapse = ", "))
return(res)
}
senatorbystate(df, "OH")
# [1] "William Jones, Daniel Graham, Jill White"
Upvotes: 0