【问题标题】:if variable name in data frame column matches names in a vector rename variable如果数据框列中的变量名称与向量重命名变量中的名称匹配
【发布时间】:2020-09-13 07:47:13
【问题描述】:

给定一个数据框和一个向量

set.seed(123)

feature <- sample(LETTERS,30,replace = T)
number<-sample(1:100,30, replace = T)
df<-data.frame(feature,number)

rename<-c("N","V","C","E")

我想扫描df$feature,如果rename 中存储的字母与df$feature 列中的一个匹配,我想将它们重命名为"other"。

我很确定这一定已经在某个地方得到了回答,不过我已经找了很长时间了。

【问题讨论】:

    标签: r variables rename


    【解决方案1】:

    您可以使用%in% 查找包含rename 的行:

    df$feature[df$feature %in% rename] <- "other"
    

    如果df$feature 是factor 并且在关卡中不包含other,您需要在与它们交换之前将other 添加到关卡:

    levels(df$feature) <- unique(c(levels(df$feature), "other"))
    

    或者您将其转换为character:

    df$feature <- as.character(df$feature)
    

    【讨论】:

      【解决方案2】:

      一个使用dplyr的选项:

      df %>%
        mutate(feature = str_replace(feature, paste(rename, collapse = "|"), "other"))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-11-17
        • 2019-08-14
        • 1970-01-01
        • 2012-04-28
        • 1970-01-01
        • 1970-01-01
        • 2012-07-31
        • 1970-01-01
        相关资源
        最近更新 更多