2013-12-16 82 views
0

具有以下格式的TXT文件分离两个一个文件:使用时间戳

2011-01-01 00:00:00 text text text text 
2011-01-01 00:01:00 text text text text 
text 
2011-01-01 00:02:00 text text text text 
.... 
.... 
.... 
.... 
2011-01-02 00:00:00 text text text text 
2011-01-02 00:01:00 text text text text 

所有文件中包含的两个日历天的数据。 是否可以将文件分成两个不同的文件,每个文件一个?

+0

要在R中输入数据吗?或者你只是想分割文件? – Thomas

+0

拆分它们并将它们保存到2个不同的txt文件中 – foc

+0

文件是否已排序?是否有需要复制到这两个文件的标题? – Thomas

回答

1
dat <- readLines(textConnection(" 2011-01-01 00:00:00 text text text text 
    2011-01-01 00:01:00 text text text text text 
    2011-01-01 00:02:00 text text text text 
    2011-01-02 00:00:00 text text text text 
    2011-01-02 00:01:00 text text text text")) 

grouped.lines <- split(dat, substr(dat, 1,11)) 
grouped.lines 
$` 2011-01-01` 
[1] " 2011-01-01 00:00:00 text text text text"  
[2] " 2011-01-01 00:01:00 text text text text text" 
[3] " 2011-01-01 00:02:00 text text text text"  

$` 2011-01-02` 
[1] " 2011-01-02 00:00:00 text text text text" 
[2] " 2011-01-02 00:01:00 text text text text" 

它更有效地处理这些作为一个单独的列表项目。如果将它们分成不同的对象,将会产生问题。它们可以通过文本名称或数字引用进行访问。 (但请注意,如果您的文本文件中包含前导空格,则需要使用前导空格。)

1

您将不得不阅读文件的所有行。

,你可以尝试这样做使用

library(package=reshape) 

则函数read.table可能有助于

那么你将有比较所有行,并将它们在两个新文件

+0

这是一条评论/建议,不是答案。 – Thomas

2

读出的数据写回in with read.table()

我们应该有一个data.frame类似于:

df <- data.frame(d = c("2011-01-01 00:00:00", "2011-01-01 00:01:00"), x = 0:1) 

申请拆分()

dfl <- split(df, df$d) 

地图write.table分裂

Map(write.table, dfl, file = paste(names(dfl), "txt", sep = "."), row.names = FALSE, sep = ";") 
+0

请注意,它似乎像OP希望按日期分割,而不是日期时间。 – Henrik