使用dplyr将数据框中的分类 "其他 "值转换为NA。

问题描述 投票:0回答:1

trial <- data.frame(c("A", "B", "C", "other"), c("a","b","Others","d"))

数据框架中有2个分类变量(属性)。我想把 "其他 "这个值重新编码为NA。我按照这里的链接。https:/cran.r-project.orgwebpackagesnaniarvignettesreplace-with-na.html。enter image description here

na_strings <- c("other", "Others")
trial %>%
  replace_with_na_all(condition = ~.x %in% na_strings)

然而,"其他 "值确实变成了NA,但所有其他字符都变成了数字。我希望其余的值保持字符。我应该怎么做?先谢谢你了。

r dplyr na
1个回答
1
投票

下面是一个简单的 dplyr 的解决方案。

library(dplyr)
library(naniar)

trial %>%
  mutate_if(is.factor,as.character) %>%
  replace_with_na_all(condition = ~.x %in% na_strings)

你只需要把你的变量类从因子改成字符就可以了。replace_with_na_all 函数。


0
投票

你可以使用基础R。

trial[sapply(trial, `%in%`, na_strings)] <- NA

或者只使用 dplyr 要做到这一点。

library(dplyr)
trial %>% mutate_all(~replace(., . %in% na_strings, NA))

#  col1 col2
#1    A    a
#2    B    b
#3    C <NA>
#4 <NA>    d

数据

trial <- data.frame(col1 = c("A", "B", "C", "other"), 
                    col2 = c("a","b","Others","d"))
© www.soinside.com 2019 - 2024. All rights reserved.