确定适当组的功能

时间:2017-02-23 18:02:54

标签: r function

我有以下数据:

DF <- data.frame(Members = c("Eva", "Charlie1", "Fred", "Charlie2", "Adam", "Eva", "Charlie2", "David", "Adam", "David", "Charlie1"))

如果成员名称符合某个条件,我想创建一个返回特定值的函数:

  1. 返回&#34; Group1&#34;如果会员名称等于Eva或Adam
  2. 返回&#34; Group2&#34;如果成员名称包含字符串&#34; Charlie&#34;
  3. 返回&#34; Group3&#34;如果成员名称不是前两个规则中的任何一个
  4. 我想返回&#34; Group1&#34;,&#34; Group2&#34;,&#34; Group3&#34;进入DF的新专栏,名为&#34; Teams&#34;

    我已经使用以下代码完成了它,但我对如何使用函数完成它感兴趣

    DF$Team <- with(DF, ifelse((DF$Members=="Eva"|DF$Members=="Adam"),"Group1",
                           ifelse((grepl("Charlie", DF$Members)),"Group2","Group3")))
    

2 个答案:

答案 0 :(得分:1)

你的意思是创建一个功能吗?有点像这样:

DF <- data.frame(Members = c("Eva", "Charlie1", "Fred", "Charlie2", "Adam", "Eva", "Charlie2", "David", "Adam", "David", "Charlie1"))

get_group <- function(data=DF, Members=Members) {
  with(DF, ifelse((DF$Members=="Eva"| DF$Members=="Adam"),"Group1",
                  ifelse((grepl("Charlie", DF$Members)),"Group2","Group3")))
}



DF$Group <- get_group(data = DF, Members = Members)

答案 1 :(得分:0)

也许你的意思是:

group_function <- function(name_string) {
    if (name_string == "Eva" | name_string == "Adam")
        return("Group 1")
    if (grepl("Charlie", name_string))
        return("Group 2")
    return("Group 3")
 }

然后在每个成员上调用此函数

DF$Team <- sapply(DF$Members, group_function)
DF

#    Members    Team
#1       Eva Group 1
#2  Charlie1 Group 2
#3      Fred Group 3
#4  Charlie2 Group 2
#5      Adam Group 1
#6       Eva Group 1
#7  Charlie2 Group 2
#8     David Group 3
#9      Adam Group 1
#10    David Group 3
#11 Charlie1 Group 2