이 질문을 여러 번 질문했는데 (Converting Character to Numeric without NA Coercion in R, Converting Character\Factor to Numeric without NA Coercion in R 등)이 특정 사례에서 무슨 일이 일어나는지 알 수는 없습니다 (경고 메시지 : ) 강제로 도입). 여기에 내가 재현 할 수있는 데이터가 있습니다.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 그럼 당신이 현재하고있는 것과 똑같습니다. –
혼란을 줄이기 위해 함수를 사용하는 것에 대한 조언을 주셔서 감사하지만 여전히 NA를 강요 당하고 있습니다. –