使用时间戳将一个文件分成两个

时间:2013-12-16 13:59:13

标签: r file

使用以下格式的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

所有文件都包含两个日历日的数据。 是否可以将文件分成两个不同的文件,一个用于日常文件?

3 个答案:

答案 0 :(得分:2)

使用read.table()

读取数据

我们应该有一个类似于:

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

应用split()

dfl <- split(df, df$d)

将write.table映射到分割

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

答案 1 :(得分:1)

您必须阅读该文件的所有行。

你可以尝试使用

这样做
library(package=reshape)

然后函数read.table可能有帮助

然后你必须比较所有行并将它们写回两个新文件

答案 2 :(得分: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"

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