今天我终于决定开始攀登 R 陡峭的学习曲线。我花了几个小时,设法导入了我的数据集并做了一些其他基本的事情,但是我在数据类型方面遇到了问题:包含小数的列作为整数导入,转换为 double 会更改值 .
在尝试将一个小的 csv 文件放在这里作为示例时,我发现 只有在数据文件过大时才会出现问题 (我的原始文件是一个 1048418 x 12 的矩阵,但即使“只有”5000 行我也有同样的问题。当我只有 100、1000 甚至 2000 行时,列被正确导入为 double )。
Here是一个较小的数据集(仍然是 500kb,但同样,如果数据集很小,则问题不会被复制)。代码是
> ex <- read.csv("exampleshort.csv",header=TRUE)
> typeof(ex$RET)
[1] "integer"
为什么当文件很大时返回列被导入为整数,而它显然是 double 类型?
最糟糕的是,如果我尝试将其转换为 double 值,则值会更改
> exdouble <- as.double(ex$RET)
> typeof(exdouble)
[1] "double"
> ex$RET[1:5]
[1] 0.005587 -0.005556 -0.005587 0.005618 -0.001862
2077 Levels: -0.000413 -0.000532 -0.001082 -0.001199 -0.0012 -0.001285 -0.001337 -0.001351 -0.001357 -0.001481 -0.001486 -0.001488 ... 0.309524
> exdouble[1:5]
[1] 1305 321 322 1307 41
这不是唯一导入错误的列,但我认为如果我找到一列的解决方案,我应该能够对其他列进行排序。以下是更多信息:
> sapply(ex,class)
PERMNO DATE COMNAM SICCD PRC RET RETX SHROUT VWRETD VWRETX EWRETD EWRETX
"integer" "integer" "factor" "integer" "factor" "factor" "factor" "integer" "numeric" "numeric" "numeric" "numeric"
它们应该按以下顺序排列:整数、日期、字符串、整数、 double 、 double 、 double 、整数、 double 、 double 、 double 、 double (类型可能是错误的,但希望您能理解我的意思)
最佳答案
请参阅 read.csv 的帮助:?read.csv
.这是相关部分:
colClasses: character. A vector of classes to be assumed for the
columns. Recycled as necessary, or if the character vector
is named, unspecified values are taken to be ‘NA’.
Possible values are ‘NA’ (the default, when ‘type.convert’ is
used), ‘"NULL"’ (when the column is skipped), one of the
atomic vector classes (logical, integer, numeric, complex,
character, raw), or ‘"factor"’, ‘"Date"’ or ‘"POSIXct"’.
Otherwise there needs to be an ‘as’ method (from package
‘methods’) for conversion from ‘"character"’ to the specified
formal class.
Note that ‘colClasses’ is specified per column (not per
variable) and so includes the column of row names (if any).
祝你在学习 R 的过程中好运。这很困难,但在你通过前几个阶段后会很有趣(我承认这需要一些时间)。
试试这个并相应地修复其他人:
ex <- read.csv("exampleshort.csv",header=TRUE,colClasses=c("integer","integer","factor","integer","numeric","factor","factor","integer","numeric","numeric","numeric","numeric"), na.strings=c("."))
正如 BenBolker 指出的那样,
colClasses
可能不需要论证。但是,请注意使用 colClasses
参数可以使操作更快,尤其是对于大型数据集。na.strings
必须指定。请参阅 ?read.csv
中的以下部分: na.strings: a character vector of strings which are to be interpreted
as ‘NA’ values. Blank fields are also considered to be
missing values in logical, integer, numeric and complex
fields.
仅供引用(这不应该作为解决方案,因为最好的解决方案是一步正确导入数据):
RET
未作为整数导入。它是作为 factor
导入的.以供将来引用,如果您想转换 factor
到 numeric
, 用new_RET <-as.numeric(as.character(ex$RET))
关于r - 在 R 中导入 csv 文件/从整数转换为 double 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8381839/