我将UTF-16 Unicode文本(.txt)文件下载并保存为mac驱动器时默认为逗号分隔值(.csv)。此文件包含数字数据,其中1000个分隔符适用于大于1,000的数字。在R中加载时,此数据属于字符类。为了转换为数字类,我执行以下操作:
tx <- read.table("/Users/username/Desktop/report.csv",sep="\t", dec = ".", fileEncoding = "UTF-16LE", fill = T, skip=1 , quote="", header=T, stringsAsFactors = FALSE)
tx$Cost <- gsub("\\,", replacement = "", x = tx$Cost)
tx$Cost <- as.numeric(tx$Cost)
Warning message:
NAs introduced by coercion
使用head(subset())函数进行汇总时,以下是我仍然无法转换为数字类的结果:
**Orig after_gsub as.numeric**
1 95.31 95.31 95.31
2 992.77 992.77 992.77
3 "1,719.68" "1719.68" NA
4 "3,135.79" "3135.79" NA
5 111.91 111.91 111.91
6 305.12 305.12 305.12
有人可以帮助我使用as.numeric()将它们转换为数字类吗?
答案 0 :(得分:2)
使用setClass
,setAs
和colClasses
:
library(methods)
setClass("chr.w.commas", contains=numeric())
setAs("character", "chr.w.commas", function(from)
as.numeric(gsub("\\,", "",from )) )
dat <- read.table(text="Orig after_gsub num
1 '95.31' '95.31' '95.31'
2 992.77 992.77 992.77
3 '1,719.68' '1719.68' NA
4 '3,135.79' '3135.79' NA
5 111.91 111.91 111.91
6 305.12 305.12 305.12", header=TRUE, colClasses="chr.w.commas")
str(dat)
'data.frame': 6 obs. of 3 variables:
$ Orig : num 95.3 992.8 1719.7 3135.8 111.9 ...
$ after_gsub: num 95.3 992.8 1719.7 3135.8 111.9 ...
$ num : num 95.3 992.8 NA NA 111.9 ...
答案 1 :(得分:1)
谢谢大家帮助过这里。我实际上发现我的加载函数是问题,并且以下代码从一开始就正确地读取数据。
read.csv(filename, sep="\t", fileEncoding="UTF-16", skip=1)
答案 2 :(得分:0)
我怀疑gsub无法正常使用您的UTF-16字符串。也许你应该在进行替换之前转换字符串。请尝试以下方法:
tx <- read.table("/Users/username/Desktop/report.csv",sep="\t", dec = ".", fileEncoding = "UTF-16LE", fill = T, skip=1 , quote="", header=T, stringsAsFactors = FALSE)
tx$Cost <- iconv(tx$Cost,"UTF-16","ASCII",sub='')
tx$Cost <- gsub("\\,", replacement = "", x = tx$Cost)
tx$Cost <- as.numeric(tx$Cost)