【发布时间】:2016-07-26 10:12:21
【问题描述】:
我知道这个问题已被问过很多次(Converting Character to Numeric without NA Coercion in R、Converting Character\Factor to Numeric without NA Coercion in R 等),但我似乎无法弄清楚在这个特殊情况下发生了什么(警告消息: 由强制引入的 NA)。这是我正在使用的一些可重现的数据。
#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)
Above 返回所有 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))
这创建了一个数字列表,因此它显然没有按照我的想法转换字符串。非常感谢任何帮助。
【问题讨论】:
标签: r class character converter