简体   繁体   中英

function to return something based on input using R

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

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"

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

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM