将字符串转换为R中的数值

时间:2015-11-07 04:07:39

标签: r character numeric coercion

我正在读取R中的.csv excel文件并提取我的数据的第5列。我得到一个字符串,但我需要将字符串bmi2014转换为数值而不会丢失信息。这是我到目前为止所尝试的:

options(stringsAsFactors = FALSE)
setwd("~/CAD Project")
bmi <- read.csv("~/CAD Project/BMI sex and province.csv")
bmi <- bmi[8:46 , ] #removing rows I don't need
bmi <- bmi[, 2:6] #removing columns I don't need
bmi2014 <- bmi[, 5]
bmi2014
[1] "272,818"   "146,959"   "125,859"   "65,238"    "32,132"    "33,106"        
"443,317"   "234,307" "209,010"   "355,959"   "192,160"   "163,799"      
"3,226,705" "1,865,444" "1,361,261" "5,508,224" "3,133,853" "2,374,371"  
"533,910"   "296,162"   "237,748"   "446,312"   "254,005"   "192,307"  
[25] "1,658,172" "984,981"   "673,190"   "1,667,339" "990,920"   "676,418"        
"15,453"    "8,482" "6,971"     "19,607"    "11,312"    "8,294"     "9,469"           
"5,187"     "4,282"     
mydata <- as.numeric(as.character(bmi2014))
Warning message:
NAs introduced by coercion 

我尝试过使用type.convert和

 as.matrix(sapply(bmi2014, as.numeric), na.rm = TRUE) 

但似乎无法解决此问题,因为返回了NA值。还有什么我可以尝试,以便我有数字列表272,818,146,959等...谢谢!

1 个答案:

答案 0 :(得分:2)

问题是逗号(,)。在转换为数字之前,您必须使用<div id="wrapper"><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer eu dui et erat</p></div>删除它们。

gsub