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!

有帮助吗?

解决方案 2

On linux and data.table 1.8.11 I'd do:

fread("sed -r 's/(([^ ]+ +){7})/\\1\\n/g' yourfile | sed 's/ $//'")

其他提示

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

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"
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top