在r中将字符转换为没有NA的数字

Convert character to numeric without NA in r

我知道这个问题已经被问过很多次(Converting Character to Numeric without NA Coercion in R, Converting Character\Factor to Numeric without NA Coercion in R,等等)但我似乎无法弄清楚在这个特殊情况下发生了什么(警告消息: 强制引入的 NAs)。这是我正在处理的一些可重现的数据。

#dependencies
library(rvest)
library(dplyr)
library(pipeR)
library(stringr)
library(translateR)

#scrape data from website
url <- "http://irandataportal.syr.edu/election-data"
ir.pres2014 <- url %>%
  read_html() %>%
  html_nodes(xpath='//*[@id="content"]/div[16]/table') %>%
  html_table(fill = TRUE)
ir.pres2014<-ir.pres2014[[1]]
colnames(ir.pres2014)<-c("province","Rouhani","Velayati","Jalili","Ghalibaf","Rezai","Gharazi")
ir.pres2014<-ir.pres2014[-1,]

#Get rid of unnecessary rows
ir.pres2014<-ir.pres2014 %>%
  subset(province!="Votes Per Candidate") %>%
  subset(province!="Total Votes")

#Get rid of commas
clean_numbers = function (x) str_replace_all(x, '[, ]', '')
ir.pres2014 = ir.pres2014 %>% mutate_each(funs(clean_numbers), -province)

#remove any possible whitespace in string
no_space = function (x) gsub(" ","", x)
ir.pres2014 = ir.pres2014 %>% mutate_each(funs(no_space), -province)

这就是我开始出错的地方。我尝试了以下每一行代码,但每次都得到了所有 NA。例如,我首先尝试将第二列 (Rouhani) 转换为数字:

#First check class of vector
class(ir.pres2014$Rouhani)

#convert character to numeric

ir.pres2014$Rouhani.num<-as.numeric(ir.pres2014$Rouhani)

以上 returns 是所有 NA 的向量。我也试过:

as.numeric.factor <- function(x) {seq_along(levels(x))[x]}
ir.pres2014$Rouhani2<-as.numeric.factor(ir.pres2014$Rouhani)

并且:

ir.pres2014$Rouhani2<-as.numeric(levels(ir.pres2014$Rouhani))[ir.pres2014$Rouhani]

并且:

ir.pres2014$Rouhani2<-as.numeric(paste(ir.pres2014$Rouhani))

所有这些 return NA。我还尝试了以下方法:

ir.pres2014$Rouhani2<-as.numeric(as.factor(ir.pres2014$Rouhani))

这创建了一个单位数字列表,所以它显然没有按照我想要的方式转换字符串。非常感谢任何帮助。

原因是 看起来像 数字前的前导 space:

> ir.pres2014$Rouhani
 [1] " 1052345" " 885693"  " 384751"  " 1017516" " 519412"  " 175608"  …

只需在转换前将其删除即可。由于这个字符实际上不是 space,它是别的东西,情况变得复杂了:

mystery_char = substr(ir.pres2014$Rouhani[1], 1, 1)
charToRaw(mystery_char)
# [1] c2 a0

我不知道它来自哪里,但它需要被替换:

str_replace_all(x, rawToChar(as.raw(c(0xc2, 0xa0))), '')

此外,您可以通过一次对所有列应用相同的转换来简化代码:

mystery_char = rawToChar(as.raw(c(0xc2, 0xa0)))
to_replace = sprintf('[,%s]', mystery_char)
clean_numbers = function (x) as.numeric(str_replace_all(x, to_replace, ''))
ir.pres2014 = ir.pres2014 %>% mutate_each(funs(clean_numbers), -province)