用单行将文件读取到fread或read.table中的R中 [英] read file with single line into R in fread or read.table

查看:64
本文介绍了用单行将文件读取到fread或read.table中的R中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将txt文件读入R

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

此文件中没有\ n,我想要的只是一个包含这些信息的数据表.

there're no \n in this file, and all the what I want is a data.table incorporating these information

像这样:

 1 NYC    2013-12-30 82 PM2.5  Ⅱ fair
 2 London 2013-12-30 66 PM10.0 Ⅱ good

幸运的是,文件中没有NA,我也确定每个观测值都有7个字段.我可以使用fread来实现吗?

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?

还是read.table?

or read.table?

我尝试过

test <- read.table("1.txt) # the file name..
test <- matrix(test, ncol = 7)

scan as.array .全部失败.

您能给些建议吗?

非常感谢!

推荐答案

在linux和 data.table 1.8.11上,我会这样做:

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

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

这篇关于用单行将文件读取到fread或read.table中的R中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆