R - 用 NA 替换特定值内容

R - Replace specific value contents with NA

我有一个相当大的数据框,其中有多个代表缺失数据的“-”。数据框由多个 Excel 文件组成,无法使用 "na.strings =" 或替代函数,所以我不得不用“-”表示导入它们。

如何用 NA /缺失值替换数据框中的所有“-”?数据框由 200 列字符、因子和整数组成。

到目前为止我已经尝试过:

sum(df %in c("-"))
returns: [1] 0

df[df=="-"] <-NA #does not do anything

library(plyr)
df <- revalue(df, c("-",NA))
returns: Error in revalue(tmp, c("-", NA)) : 
  x is not a factor or a character vector.

library(anchors)
df <- replace.value(df,colnames(df),"-",as.character(NA))
Error in charToDate(x) : 
  character string is not in a standard unambiguous format

数据框由 200 列字符、因子和整数组成,所以我明白为什么最后两个不能正常工作。任何帮助将不胜感激。

这里有一个解决方案:

> library(dplyr)
> test <- tibble(x = c('100', '20.56', '0.003', '-', '  -'),  y = 5:1)
> makeNA <- function(x) str_replace(x,'-',NA_character_)
> mutate_all(test, funs(makeNA))
# A tibble: 5 x 2
  x     y    
  <chr> <chr>
1 100   5    
2 20.56 4    
3 0.003 3    
4 NA    2    
5 NA    1  

由于您已经在使用 tidyverse 函数,因此您可以轻松地在管道中使用 dplyr 中的 na_if

比如我有一个数据集,其中999用于填写一个non-answer:

df <- tibble(
    alpha = c("a", "b", "c", "d", "e"), 
    val1 = c(1, 999, 3, 8, 999), 
    val2 = c(2, 8, 999, 1, 2))

如果我想改变 val1 所以 999 是 NA,我可以这样做:

df %>% 
    mutate(val1 = na_if(val1, 999))

在你的情况下,听起来你想要跨多个变量替换一个值,所以使用 mutate_atmutate_if 会更合适:

df %>%
    mutate_at(vars(val1, val2), na_if, 999)

val1val2 中的所有 999 实例替换为 NA,现在看起来像这样:

# A tibble: 5 x 3
  alpha  val1  val2
  <chr> <dbl> <dbl>
1 a        1.    2.
2 b       NA     8.
3 c        3.   NA 
4 d        8.    1.
5 e       NA     2.

我认为最简单的解决方案是使用基本 R 函数 is.na<-。它旨在准确解决该问题。

首先,补一些数据。然后将所需的值设置为 NA.

set.seed(247)    # make the results reproducible

df <- data.frame(X = 1:10, Y = sample(c("-", letters[1:2]), 10, TRUE))

is.na(df) <- df == "-"
df
#    X    Y
#1   1    a
#2   2    b
#3   3    b
#4   4    a
#5   5 <NA>
#6   6    b
#7   7    a
#8   8 <NA>
#9   9    b
#10 10    a