2016-07-26 34 views
1

我知道这个问题已经被问了很多次(Converting Character to Numeric without NA Coercion in RConverting Character\Factor to Numeric without NA Coercion in R等),但我似乎无法找出什么在这个特定的情况下回事(警告消息: 来港由胁迫引入)。这是我正在处理的一些可重复的数据。转换字符为数字,而不NA r中

#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) 

和:

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

和:

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

所有这些回报NA的。我也试过如下:

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

创建单个数字的列表,以便它显然不是在方式转换字符串我的想法。任何帮助深表感谢。

回答

3

原因是号码前是什么样子前导空格:

> 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) 
+0

我忘了提我试过,以及使用''$ ir.pres2014 Rouhani <-gsub(”‘’ “,ir.pres2014 $ Rouhani)''但s直到相同 –

+1

@CyrusMohammadian嗯,这就和你现在正在做的一样。 –

+0

感谢您使用函数来减少混乱的提示,但我仍然被强制执行。 –