如何将行的其余部分分配到R中的单个列

如何将行的其余部分分配到R中的单个列,r,R,假设我们有一个包含内容的文件: date time data 2015-02-28 09:00:00,173 Some data here 2015-02-28 09:10:00,251 Anoter data here 我考虑使用Read .table < /P> read.table("someFile", header=T, sep=" ") 我不知道如何将行尾(“此处的某些数据”字符串)分配给单列您可以使用读取行读取文件,将字符串前的空格替换为,,然后尝试使用读取表 dat1 <

假设我们有一个包含内容的文件:

date time data
2015-02-28 09:00:00,173 Some data here
2015-02-28 09:10:00,251 Anoter data here

我考虑使用Read .table < /P>

read.table("someFile", header=T, sep=" ")

我不知道如何将行尾(“此处的某些数据”字符串)分配给单列

您可以使用
读取行
读取文件,将字符串前的空格替换为
,然后尝试使用
读取表

dat1 <- read.table(text=sub('(?<=\\d) (?=[A-Za-z])', ',',
  lines[-1], perl=TRUE), header=FALSE, stringsAsFactors=FALSE, sep=",")
colnames(dat1) <-  c('datetime', 'Val', 'Col2')
dat1
#             datetime Val             Col2
#1 2015-02-28 09:00:00 173   Some data here
#2 2015-02-28 09:10:00 251 Anoter data here

dat1由于您的分隔符不一致(您有“,”和“,”分隔符),您必须(至少)执行两次。有几种选择,但在我看来,这是最具适应性和可读性的选择:

1) 将整个文件作为字符串列表导入:

   datRaw <- readLines("someFile")[[1]]

datRaw首先,您的“数据”列似乎在使用空格(因为它是一个字符串)。如果要支持此操作,需要将分隔符更改为其他分隔符,如逗号:

date,time,number,data
2015-02-28,09:00:00,173,Some data here
2015-02-28,09:10:00,251,Another data here
……和:

> read.table(someFile, header=T, sep=",")
现在它读对了

您可以使用
$column
读取特定列,并使用
as.vector
将“数据”列作为向量:

> mydata <- as.vector(read.table(someFile, header=TRUE, sep=",")$data)
> mydata
[1] "Some data here"    "Another data here"
> mydata[1]
[1] "Some data here"
>我的数据我的数据
[1] “此处有一些数据”“此处有另一个数据”
>mydata[1]
[1] “这里有一些数据”

谢谢您的回复。文件太大,无法编辑。但我明白,要实现我的目标,没有简单的方法
> read.table(someFile, header=T, sep=",")
> mydata <- as.vector(read.table(someFile, header=TRUE, sep=",")$data)
> mydata
[1] "Some data here"    "Another data here"
> mydata[1]
[1] "Some data here"