【问题标题】:How to use If function in R to create a column using multiple conditions如何在 R 中使用 If 函数使用多个条件创建列
【发布时间】:2020-07-14 16:28:50
【问题描述】:

我对 R 不熟悉,我需要你的帮助来解决这个问题, 我有一个由 25 个变量(25 列)组成的数据框,名为 df 简化

 name   experience      Club        age       Position 
 luc          2         FCB         18        Goalkeeper
 jean         9         Real        26        midfielder
 ronaldo      14        FCB         32        Goalkeeper
 jean         9         Real        26        midfielder
 messi        11        Liverpool   35        midfielder
 tevez        6         Chelsea     27        Attack
 inzaghi      9         Juve        34        Defender
 kwfni        17        Bayern      40        Attack
 Blabla       9         Real       25        midfielder
 wdfood      11        Liverpool   33        midfielder
 player2      7         Chelsea     28       Attack
 player3     10         Juve       34        Defender
 fgh         17        Bayern      40        Attack

我想在这个数据框中添加一个名为“国家”的列。这个新列考虑了不同的条件。

Juve      Italy
FCB       Spain
Real      Spain
Chelsea   England
Liverpool England
Bayern    Germany

假设俱乐部是 FCB 还是 Real,那么国家/地区的价值是西班牙 df$Country 的输出应该如下

Country
Spain 
Spain 
Spain 
Spain 
England
England 
Italy 
Germany
Spain 
England 
England
Italy 
Germany

我开始做的代码如下

df$country=ifelse(df$Club=="FCB","spain",    df$Club=="Real","Spain" ......)

但这似乎是错误的。 知道我的真实数据集在“俱乐部”列中有超过 250 个不同的值 而在“国家”中有30多个

手动操作似乎太长了。

请您在这方面帮助我。

【问题讨论】:

    标签: r database if-statement merge multiple-columns


    【解决方案1】:

    你知道如何在for 循环中使用if-else 语句吗?这将是最简单的出路。

    类似这样的:

    df <- data.frame(name = c("a", "b", "c"),
                     Club = c("FCB", "Real", "Liverpool"),
                     stringsAsFactors = FALSE)
    
    
    for(i in 1:nrow(df)){
      if(df$Club[i] == "FCB" | df$Club[i] == "Real"){
        df$country[i] <- "Spain"
      } else if(df$Club[i] == "Liverpool"){
        df$country[i] <- "England"
      } else{
        df$country[i] <- NA
      }
    }
    
    df
    #   name      Club country
    # 1    a       FCB   Spain
    # 2    b      Real   Spain
    # 3    c Liverpool England
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-16
      • 2019-06-24
      • 2019-11-29
      • 2023-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多