如果列表中的关键字,则创建虚拟变量

时间:2016-04-06 19:49:42

标签: r

我遇到了以下问题: 我正在尝试创建一个虚拟变量,如果团队是最高的则将打印1,否则为0。顶级球队名单是:(阿森纳,切尔西,曼城,曼尼,利物浦) 原始数据season_2015:

                    team       opponent goals home 
HomeTeam         Arsenal Crystal Palace     2    1   
AwayTeam  Crystal Palace        Arsenal     1    0   
HomeTeam1      Leicester        Everton     2    1   
AwayTeam1        Everton      Leicester     2    0   
HomeTeam2     Man United        Swansea     1    1   
AwayTeam2        Swansea     Man United     2    0   

我的目标是创造变量" top"如果团队在单词表中,那将会加1。

                    team       opponent goals home top
HomeTeam         Arsenal Crystal Palace     2    1   1
AwayTeam  Crystal Palace        Arsenal     1    0   0
HomeTeam1      Leicester        Everton     2    1   0
AwayTeam1        Everton      Leicester     2    0   0
HomeTeam2     Man United        Swansea     1    1   1
AwayTeam2        Swansea     Man United     2    0   0

我试过的代码是(我知道代码是错误的):

wordlist <- c("Arsenal", "Man City", "Man United", "Liverpool", "Chelsea")
for(i in wordlist){season_2015[paste("top")] <- ifelse(top == wordlist,1,0)}

我是R的新手,感谢任何帮助。提前谢谢。

1 个答案:

答案 0 :(得分:0)

如果您的数据看起来像这样

>season_2015 <- read.csv("season_2015.csv")
>season_2015

  home_away           team       opponent goals home
1  HomeTeam        Arsenal Crystal Palace     2    1
2  AwayTeam Crystal Palace        Arsenal     1    0
3 HomeTeam1      Leicester        Everton     2    1
4 AwayTeam1        Everton      Leicester     2    0
5 HomeTeam2     Man United        Swansea     1    1
6 AwayTeam2        Swansea     Man United     2    0

您的顶级团队数据如下所示:

>topteams <- c("Arsenal", "Man City", "Man United", "Liverpool", "Chelsea")

然后你可以这样做:

>season_2015$top <- ifelse(season_2015$team %in% topteams, 1, 0)
>season_2015

  home_away           team       opponent goals home top
1  HomeTeam        Arsenal Crystal Palace     2    1   1
2  AwayTeam Crystal Palace        Arsenal     1    0   0
3 HomeTeam1      Leicester        Everton     2    1   0
4 AwayTeam1        Everton      Leicester     2    0   0
5 HomeTeam2     Man United        Swansea     1    1   1
6 AwayTeam2        Swansea     Man United     2    0   0