繁体   English   中英

R:将字符串值更改为 NA,出现强制错误

[英]R: changing String values to NA, getting coercion error

我有一个名为data的数据集,如下所示:

  Year  Population
1 2005  3000  
2 2006  4000 
3 2007  5000
4 2008  6000
5 2009  NP
6 2010  NP
7 2011  NP
8 2012  6000
9 2013  3000

我想获得计数列的平均值,但由于 NP 不是数值,我想将其转换为 NA。 我使用了以下代码:

data %>% mutate(Count = as.numeric(Count))

但是,我收到一条错误消息,说 NA 是由强制引入的。 如何将所有值转换为数字并避免出现此错误?

这不是错误,只是警告消息。

1)我们可以用suppressWarnings包装

data$Count <- suppressWarnings(as.numeric(data$Count)))

例如

v1 <- c(1, 2, 3, 'a', 'b')
suppressWarnings(as.numeric(v1))
#[1]  1  2  3 NA NA

最直接的转换方法是应用as.numeric而无需任何其他操作。 这里的warning是一个友好的信息。

2)如果我们想在没有收到警告的情况下转换为numeric ,另一种选择是将NP替换为 `NA

library(dplyr)
data %>%
      mutate(Count = as.numeric(na_if(Count, 'NP')))

3)或者另一种选择是根据非数字字符将元素replaceNA

library(stringr)
data %>% 
    mutate(Count = as.numeric(replace(Count,
           str_detect(Count, '\\D'), NA)))

我们可以在summarisemutate获得汇总的输出

data %>%
      mutate(Count = sum(as.numeric(replace(Count, str_detect(Count, '\\D'), NA)), na.rm = TRUE))

有很多方法可以做到这一点。

几种方法包括 -

  1. 使用grepl我们可以将Population列中具有非数字字符的所有值转换为NA并将其转换为数字。
df$Population[grepl('\\D', df$Population)] <- NA
df$Population <- as.numeric(df$Population)
df

#  Year Population
#1 2005       3000
#2 2006       4000
#3 2007       5000
#4 2008       6000
#5 2009         NA
#6 2010         NA
#7 2011         NA
#8 2012       6000
#9 2013       3000
  1. 使用parse_number
df$Population <- readr::parse_number(df$Population)

完成此操作后,您可以像往常一样使用na.rm = TRUE执行所有数学运算。

mean(df$Population, na.rm = TRUE)
sum(df$Population, na.rm = TRUE)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM