使用 read.table 导入数据集,其中数据不均匀

Import of data set using read.table where data is uneven

我从 MASS 中获取了 mtcars 数据集并进行了一些修改。从一个包转到另一个包后,我终于将数据输入记事本,在那里我仔细确保空格是分隔符。我的问题是这样创建的文件不会读入。我有一个测试文件,读入很好。

你能解释一下错误信息告诉我的是什么吗?谢谢你。错误消息和使用的代码如下。

TEST.txt
120 140 7.5
140 150 8.5

mtcars2=read.table(file="TEST.txt",header=FALSE)
mtcars2
#    V1  V2  V3
# 1 120 140 7.5
# 2 140 150 8.5  OK

mtcars2.txt 问题数据集

160 110 2.62
160 110 2.875
160 110 2.32
160 110 3.215
160 115 3.44

mtcars2=read.table("c:\data\mtcars2.txt",header=FALSE)

Warning messages: 1: In read.table("c:\data\mtcars2.txt", header = FALSE) : line 1 appears to contain embedded nulls ... 6: In scan(file = file, what = what, sep = sep, quote = quote, dec = dec, : embedded nul(s) found in input NOT OK

我还尝试了以下方法:

mtcars2=read.table("c:\data\mtcars2.txt",fill=T,header=FALSE)

我用了 cut/paste,效果很好。然后我在第一个 space 之前放了一个空值,我得到了:

line 1 appears to contain embedded nulls.  

我怀疑您修改了文件,使输出的值像 'c' strings 一样以零结尾;或 Unicode (16 bit) 也会带来麻烦,因为它有零。
要检查文件中每个字节的内容,您可以做的一件事是使用 UNIX/Linux od 程序:

od -c filename  

示例输出:

0000000000     1   6  [=12=]  [=12=]       1   1  [=12=]       2   .   6   2  \r  \n   1
0000000020     6  [=12=]       1   1  [=12=]       2   .   8   7   5  \r  \n   1   6
0000000040    [=12=]       1   1  [=12=]       2   .   3   2  \r  \n   1   6  [=12=]
> dss <- read.table(header=TRUE, text='
+ 160    110    2.62
+ 160    110    2.875
+ 160    110    2.32
+ 160    110    3.215
+ 160    115    3.44
+ ')
> dss
  X160 X110 X2.62
1  160  110 2.875
2  160  110 2.320
3  160  110 3.215
4  160  115 3.440
> 

header=TRUE 可能会被删除。