简体   繁体   English

R中的ifelse语句不起作用-列结果不正确

[英]ifelse Statement in R Not Working - Incorrect Column Result

I have a df: 我有一个df:

Year | 年份 Stage | 舞台 Home.Team.Name | 队名| Home.Team.Goals | 主页。团队。目标| Away.Team.Name | 客队名称| Away.Team.Goals Away.Team.Goals

1998 | 1998 | Group A| A组| Brazil..................| 巴西.................. | 2............................ | 2 ..................................... | Scotland............... | 苏格兰...... 1 1

and so on. 等等。

What I'm trying to do is create a new column based off the result of each game. 我想做的是根据每个游戏的结果创建一个新列。 So the winners name appears in a new column. 因此,获奖者的姓名会出现在新列中。 The code I currently have is: 我目前拥有的代码是:

RecentWorldCups$Game.Winner <- ifelse(RecentWorldCups$Home.Team.Goals>RecentWorldCups$Away.Team.Goals, RecentWorldCups$Home.Team.Name,
                                      ifelse(RecentWorldCups$Away.Team.Goals>RecentWorldCups$Home.Team.Goals, RecentWorldCups$Away.Team.Name,
                                             "Draw"))

The result of this is that it gives me a number (perhaps a factor number?) instead of the name of the team. 这样的结果是给了我一个数字(也许是因子数字?),而不是团队的名字。

Anyone able to help? 有人能帮忙吗? Cheers 干杯

You need to extract the character level value from your factor columns. 您需要从因子列中提取字符级别值。 Try this: 尝试这个:

df <- RecentWorldCups     # for readability of your code

df$Game.Winner <- ifelse(df$Home.Team.Goals > df$Away.Team.Goals,
   levels(df$Home.Team.Name)[df$Home.Team.Name],
   ifelse(df$Away.Team.Goals > df$Home.Team.Goals,
       levels(df$Away.Team.Name)[df$Away.Team.Name],
       "Draw")
)

If you find it cumbersome to do these factor conversions, then one workaround would be to create your data frame with all strings set to not be factors, eg something like this: 如果发现进行这些因子转换很麻烦,那么一种变通方法是创建所有字符串都设为非因子的数据框,例如:

RecentWorldCups <- data.frame(Home.Team.Goals=c(...), ..., stringsAsFactors=FALSE)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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