【问题标题】:Changing content of a character column based on its row value in R根据 R 中的行值更改字符列的内容
【发布时间】:2020-11-20 00:57:38
【问题描述】:

我的数据框中有一个分类列,其中包含 14 种不同的字符串可能性。我想创建一个只保留 3s 字符串并将所有剩余字符串折叠为“其他”的新变量。

我想通过首先创建一个向量来执行此操作,该向量具有出现 3 个类别之一的行号,然后将它们组合起来:

x <- which(binarydata1$Sector=="Independent artist")
y <- which(binarydata1$Sector=="Arts and Culture")
z <- which(binarydata1$Sector=="Community or Social Services")
object <- c(x, y, z) #This contains all the row values of the strings listed, the ones I don't want to change ....

我可以用它来调用列中不等于这些值的行值,以便我可以用其他替换这些字符串吗?还是我认为这一切都错了?

【问题讨论】:

  • 请发布有代表性的数据以供使用。您可以对包含您感兴趣的Sector 值的数据子集使用dput(bindarydata1)dput 来执行此操作。请参阅minimal reproducible example

标签: r dplyr


【解决方案1】:

你试过简单的ifelse吗?

values <- c("Independent artist", "Arts and Culture", "Community or Social Services")
x <- ifelse(binarydata1$Sector %in% values,
            binarydata1$Sector,
            "Other")

【讨论】:

    【解决方案2】:

    您可以使用forcats::fct_other,它将仅保留您指定的值,并将其余值更改为“其他”。

    binarydata1$Sector <- forcats::fct_other(binarydata1$Sector, 
                          keep = c("Independent artist", 
                                  "Arts and Culture","Community or Social Services"))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-22
      • 2023-01-08
      • 2022-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-05
      • 1970-01-01
      相关资源
      最近更新 更多