1
我知道这个问题已经被问了很多次(Converting Character to Numeric without NA Coercion in R,Converting 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))
创建单个数字的列表,以便它显然不是在方式转换字符串我的想法。任何帮助深表感谢。
我忘了提我试过,以及使用''$ ir.pres2014 Rouhani <-gsub(”‘’ “,ir.pres2014 $ Rouhani)''但s直到相同 –
@CyrusMohammadian嗯,这就和你现在正在做的一样。 –
感谢您使用函数来减少混乱的提示,但我仍然被强制执行。 –