用R读取文本文件的一半



如果我有这样的文本文件:

# This is a text file
# Here is info about the data that
# will be of an undetermined
# length
# Data set 1
1,61
2,79
3,65
4,10
5,82
# Data set 2
1,61
2,75
3,27
4,27
5,94

如何告诉R在Data set 1中阅读而不是在Data set 2中阅读?每个数据集的长度是可变的,并且是动态更新的。Data set 2将始终在如上所述的注释字符之后开始。

如果该文件保存为"70626963.txt",则有两种方法:

txt <- readLines("~/StackOverflow/9454855/70626963.txt")
read.csv(text = txt[nzchar(txt) & cumsum(!nzchar(txt)) == 1], skip = 1, header = FALSE)
#   V1 V2
# 1  1 61
# 2  2 79
# 3  3 65
# 4  4 10
# 5  5 82

read.csv(pipe("sed -ne '/Data set 1/,/Data set 2/{/Data set/d;p}' 70626963.txt"), header = FALSE)
#   V1 V2
# 1  1 61
# 2  2 79
# 3  3 65
# 4  4 10
# 5  5 82

最新更新