问题
I want to read a txt file into R
this file has only file line, like this
1 NYC 2013-12-30 82 PM2.5 Ⅱ fair 2 London 2013-12-30 66 PM10.0 Ⅱ good
there're no \n in this file, and all the what I want is a data.table incorporating these information
like this:
1 NYC 2013-12-30 82 PM2.5 Ⅱ fair
2 London 2013-12-30 66 PM10.0 Ⅱ good
Luckily, there're no NAs in the file, also I know for sure there're 7 fields for each observations. Could I achieve this using fread?
or read.table?
I tried this
test <- read.table("1.txt) # the file name..
test <- matrix(test, ncol = 7)
and scan
,as.array
. all failed.
Could you give some suggestions?
Thanks a lot!
回答1:
On linux and data.table
1.8.11 I'd do:
fread("sed -r 's/(([^ ]+ +){7})/\\1\\n/g' yourfile | sed 's/ $//'")
回答2:
The easiest thing might just be to use scan
directly. You could probably also use read.fwf
, but I think that's more complex.
> data.frame(matrix(scan('2.txt', what='character'), nrow=2, byrow=TRUE))
Read 14 items
X1 X2 X3 X4 X5 X6 X7
1 1 NYC 2013-12-30 82 PM2.5 || fair
2 2 London 2013-12-30 66 PM10.0 || good
回答3:
Here's a second way with scan
:
t(do.call(rbind, scan(text=t, what=replicate(7, character()))))
# [,1] [,2] [,3] [,4] [,5] [,6] [,7]
# [1,] "1" "NYC" "2013-12-30" "82" "PM2.5" "?" "fair"
# [2,] "2" "London" "2013-12-30" "66" "PM10.0" "?" "good"
来源:https://stackoverflow.com/questions/21990571/read-file-with-single-line-into-r-in-fread-or-read-table