【问题标题】:Replacing the values of a categorical variable using if-else condition or any other approach使用 if-else 条件或任何其他方法替换分类变量的值
【发布时间】:2020-01-20 21:28:51
【问题描述】:

这是我的数据集“调查”,其中包含“代码”作为分类变量。

ID<- seq(1:50)
Codes<- sample(c("Sat1", "Sat2", "A1", "B2", "C2", "D5", "T4"), 50, replace= TRUE)
Survey<- data.frame(Codes)

代码中的等级如下所示:

> levels(Survey$Codes)
[1] "A1"   "B2"   "C2"   "D5"   "Sat1" "Sat2" "T4"  

我想将 Codes 列中除“Sat1”和“Sat2”之外的所有值替换为新值“Sat3”。换句话说,我希望我在 Codes 中的水平是:

> levels(Survey$Codes)
[1] “Sat1” “Sat2” “Sat3”

我知道这个问题的第一部分代码,即

levels(Survey$Codes)<- c(levels(Survey$Codes), “Sat3”)

但我被困在如何处理其余代码,即如何用“Sat3”替换代码的所有值(“Sat1”和“Sat2”除外)。我正在考虑在这里使用 if-else 语句,但不确定如何为其构建代码。你能帮我解决这个问题吗?谢谢

【问题讨论】:

    标签: r if-statement r-factor


    【解决方案1】:

    怎么样

    levels(Survey$Codes)[!grepl("Sat",levels(Survey$Codes))]<-"Sat3"
    

    grepl 检查某个字符串是否出现在您的关卡中。输出:

    > levels(Survey$Codes)
    [1] "Sat3" "Sat1" "Sat2"
    
    > Survey$Codes
     [1] Sat3 Sat1 Sat3 Sat2 Sat3 Sat3 Sat3 Sat3 Sat3 Sat3 Sat3 Sat3 Sat1 Sat3 Sat2 Sat3 Sat1 Sat3 Sat1 Sat2 Sat3 Sat3 Sat3 Sat2 Sat3
    [26] Sat1 Sat3 Sat3 Sat3 Sat3 Sat3 Sat3 Sat3 Sat2 Sat3 Sat3 Sat1 Sat3 Sat3 Sat3 Sat3 Sat2 Sat3 Sat3 Sat3 Sat2 Sat3 Sat3 Sat3 Sat3
    Levels: Sat3 Sat1 Sat2
    

    【讨论】:

      【解决方案2】:

      试试这个:

      levels(Survey$Codes)[!levels(Survey$Codes) %in% c("Sat1", "Sat2")]<- "Sat3"
      
      #> levels(Survey$Codes)
      #[1] "Sat3" "Sat1" "Sat2"
      

      请注意,这是一个更通用的解决方案。例如,如果兴趣级别没有任何共同特征,grepl 解决方案将不起作用。

      【讨论】:

      • 这是我一直在寻找的简单逻辑。
      【解决方案3】:

      假设您要创建的数据框是:

      Survey <- data.frame(ID = seq(1:50),
                          Codes = sample(c("Sat1", "Sat2", "A1", "B2", "C2", "D5", "T4"), 50, replace= TRUE))
      

      您的问题的一个解决方案是添加一个名为“Sat3”的新关卡:

      levels(Survey$Codes)<- c(levels(Survey$Codes), "Sat3")
      Survey$Codes[!grepl("Sat1|Sat2", Survey$Codes)] <- "Sat3" #replace if level is either Sat1 or Sat2
      

      如果需要,您可以在此之后删除未使用的因子水平:

      Survey$Codes <- droplevels(Survey$Codes)
      

      【讨论】:

      • 效果很好。谢谢
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-31
      相关资源
      最近更新 更多