txt 文件中的列数多于列名

more columns than column name on txt file

我有这个 txt 文件,我想用这个命令在 R 中阅读这个文件:

read.table("C:/users/vatlidak/My Documents/Documents/Untitled.txt", header=TRUE)

R returns 我执行以下命令:

"more columns than column name"

txt 文件:

height Shoesize gender Location
1   181 44   male      city center
4   170 43   female    city center
5   172 43   female    city center
13  175 42   male      out of city
14  181 44   male      out of city
15  180 43   male      out of city
16  177 43   female    out of city
17  133 41   male      out of city

如果 myFile 包含 path/filename,则用逗号替换每行的前 4 段空白,然后使用 read.csv 重新读取。没有使用包。

L <- readLines(myFile) ##
for(i in 1:4) L <- sub("\s+", ",", L)
DF <- read.csv(text = L)

给予:

> DF
   height Shoesize gender    Location
1     181       44   male city center
4     170       43 female city center
5     172       43 female city center
13    175       42   male out of city
14    181       44   male out of city
15    180       43   male out of city
16    177       43 female out of city
17    133       41   male out of city

注意: 出于测试目的,我们可以用它来代替上面标记## 的行。 (请注意,SO 可以在行的开头引入空格,因此我们将其删除。)

Lines <- " height Shoesize gender Location
1   181 44   male      city center
4   170 43   female    city center
5   172 43   female    city center
13  175 42   male      out of city
14  181 44   male      out of city
15  180 43   male      out of city
16  177 43   female    out of city
17  133 41   male      out of city"

L <- readLines(textConnection(Lines))
L[-1] <- sub("^\s+", "", L[-1])

有点晚了,但我遇到了同样的问题,我尝试了它们,但我没有处理我的数据集,我只是将 csv 文件转换为 xlsx 文件,它在没有任何额外操作的情况下工作。喜欢,

library(gdata)
df <- read.xls(file, sheet = 1, row.names=1)

这可能对以后的读者有所帮助。