将字符串转换为R中的数值
Convert character string into numeric values in R
我正在读取 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 等的列表...谢谢!
问题是逗号 (,)。在转换为数字之前,您必须使用 gsub
删除它们。
bmi2014 <-c("272,818","146,959","125,859","65,238", "32,132","33,106",
"443,317","234,307","209,010")
as.numeric(gsub(",","",bmi2014))
1[1] 272818 146959 125859 65238 32132 33106 443317 234307 209010
我正在读取 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 等的列表...谢谢!
问题是逗号 (,)。在转换为数字之前,您必须使用 gsub
删除它们。
bmi2014 <-c("272,818","146,959","125,859","65,238", "32,132","33,106",
"443,317","234,307","209,010")
as.numeric(gsub(",","",bmi2014))
1[1] 272818 146959 125859 65238 32132 33106 443317 234307 209010