我有这个txt
文件,我想在R中用这个命令读取它:
read.table("C:/users/vatlidak/My Documents/Documents/Untitled.txt", header=TRUE)
R返回以下命令:
“比列名更多的列”
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
答案 0 :(得分:2)
如果myFile
包含路径/文件名,则用逗号替换每行的前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])
答案 1 :(得分:2)
有点晚了,但我有同样的问题,我尝试了但我没有在我的数据集上工作,而不是我刚刚将csv文件转换为xlsx文件,它没有任何额外的操作。喜欢,
library(gdata)
df <- read.xls(file, sheet = 1, row.names=1)
这可能有助于未来的读者。