将r中不带NA的字符转换为数字

将r中不带NA的字符转换为数字,r,class,character,converter,R,Class,Character,Converter,我知道这个问题已经被问过很多次了,等等。但我似乎无法弄清楚在这一特定案例警告信息中发生了什么: 由强制引入的NAs。这是我正在处理的一些可复制的数据 #dependencies library(rvest) library(dplyr) library(pipeR) library(stringr) library(translateR) #scrape data from website url <- "http://irandataportal.syr.edu/election-da

我知道这个问题已经被问过很多次了,等等。但我似乎无法弄清楚在这一特定案例警告信息中发生了什么: 由强制引入的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)
上面返回所有NA的向量。我还尝试:

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

以及:

所有这些都返回了NA的。我还尝试了以下方法:

ir.pres2014$Rouhani2<-as.numeric(as.factor(ir.pres2014$Rouhani))
这创建了一个单位数的数字列表,因此它显然没有按照我所想的方式转换字符串。非常感谢您的帮助。

原因是数字前有一个前导空格:

> ir.pres2014$Rouhani
 [1] " 1052345" " 885693"  " 384751"  " 1017516" " 519412"  " 175608"  …
在转换之前,只需将其移除即可。由于这个角色实际上不是一个空格,而是另一个空格,情况变得复杂了:

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)

我忘了提一下,我用ir也试过了$Rouhani@CyrusMohammadian这和你现在所做的一样。谢谢你提供了使用函数来减少混乱的技巧,但我仍然被强迫使用NA。@CyrusMohammadian是的,看更新的答案:不管什么原因,你在这里得到了一些非常奇怪的角色。
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)