函数使用R返回基于输入的内容

时间:2015-10-29 05:14:30

标签: r function for-loop vector

我需要编写一个函数来返回给定状态的参议员的名字。我是R的新手,我在编写实际功能时遇到了麻烦。鉴于此样本数据:

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") 

我正在寻找的输出是指定状态的参议员的矢量:

> William Jones, Daniel Graham, Jill White

3 个答案:

答案 0 :(得分:2)

我重构了您的senatorbystate()函数,将数据框df拆分为输入状态,从而生成一个数据帧列表,每个数据帧都与某个状态相对应。然后我聚合输入状态的名字和姓氏列并返回名字的矢量。

# 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)
}

<强>用法:

> output <- senatorbystate("OH", df)
[1] "William Jones" "Daniel Graham" "Jill White"
> output[2]
[1] "Daniel Graham"

答案 1 :(得分:2)

略小的版本,

senatorbystate <- function(state) with(df[df$state==state, ], 
                                       paste(firstname, lastname, collapse=", "))

如果要将字符数组作为输出

,请删除collapse

答案 2 :(得分:0)

Tim Biegeleisen的一个变种回答:

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"