在R语言中使用'fread'函数读取数据时,如果同时使用了'na.strings'和'colClasses'参数,则可能会出现列模式错误的情况。

5

Windows 8.1,R版本3.1.1(2014-07-10),系统x86_64,mingw32

我有一个包含大量观测值的文件(在这里)。以下是文件中的一些字符串。

Date;Time;Global_active_power;Global_reactive_power;Voltage;Global_intensity;Sub_metering_1;Sub_metering_2;Sub_metering_3
16/12/2006;17:24:00;4.216;0.418;234.840;18.400;0.000;1.000;17.000
16/12/2006;17:25:00;5.360;0.436;233.630;23.000;0.000;1.000;16.000
28/4/2007;00:20:00;0.492;0.208;236.240;2.200;0.000;0.000;0.000
28/4/2007;00:21:00;?;?;?;?;?;?;
21/12/2006;11:25:00;0.246;0.000;241.740;1.000;0.000;0.000;0.000
21/12/2006;11:26:00;0.246;0.000;241.830;1.000;0.000;0.000;0.000

NA值用“?”来表示。我正在尝试使用读取文件

epcData <- fread(dataFile,
                 sep = ";",
                 header = TRUE,
                 na.strings = "?",
                 colClasses = c("character", "character", rep("numeric", 7)),
                 stringsAsFactors = FALSE)

我收到了像这样的警告:

Bumped column 3 to type character on data row 10, field contains '?'. Coercing previously read values in this column from integer or numeric back to character which may not be lossless; e.g., if '00' and '000' occurred before they will now be just '0', and there may be inconsistencies with treatment of ',,' and ',NA,' too (if they occurred in this column before the bump). If this matters please rerun and set 'colClasses' to 'character' for this column. Please note that column type detection uses the first 5 rows, the middle 5 rows and the last 5 rows, so hopefully this message should be very rare. If reporting to datatable-help, please rerun and include the output from verbose=TRUE.

第10行是:
   28/4/2007;00:21:00;?;?;?;?;?;?;

epcData[10]

输出

         Date     Time Global_active_power Global_reactive_power Voltage
1: 28/4/2076 00:21:00                  NA                    NA      NA
   Global_intensity Sub_metering_1 Sub_metering_2 Sub_metering_3
1:               NA             NA             NA             NA

但是所有列的模式都是“字符”,即使是第3到9列(但colClasses = c(“character”,“character”,rep(“numeric”,7)))。

出了什么问题?


你使用的操作系统是什么? - Mike.Gahan
1
еҰӮжһңжҳҜLinuxжҲ–OSXпјҢдҪҝз”ЁfreadпјҲsed -i 's /пјҹ/ NA / g' yourcsv.csvпјүжҹҘжүҫе’ҢжӣҝжҚўй—®еҸ·еҸҜиғҪеҖјеҫ—еңЁfreadејҖе§ӢиҜ»еҸ–д№ӢеүҚгҖӮ - Mike.Gahan
只需阅读文档,na.string 似乎仅适用于字符串向量。这不是什么大问题。在读入数据后,只需转换为 as.numeric 即可。 - Mike.Gahan
1
@Mike.Gahan 使用read.table(dataFile,header=TRUE, sep=";", na.strings = "?", colClasses = c("character","character", rep("numeric",7)), stringsAsFactors = FALSE))时,程序可以正常运行。但是使用相同的参数时速度非常慢。 - nodm
好消息是,那个链接似乎表明 data.table 的维护者 @Arun 和 @MattDowle 正在努力改进这一点。 - Mike.Gahan
显示剩余9条评论
1个回答

2

截至今天,使用 data.table 软件包的版本 1.12.2,这已不再是问题,上述 CSV 数据的导入工作流畅无阻,并且所有问号都被替换为 NA

Original Answer 翻译成 "最初的回答"。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接