如何仅从特定文本字符串下方读取数据

问题描述 投票:0回答:2

我通常使用.txt文件,该文件在文件的开头包含数百行无关的文本。该文本出现在我需要在R中分析的列表数据的上方。两个文件之间无关文本的行数从不相同。但是,在无关内容的末尾和列表数据的开始之前,总是有一个相同的文本字符串(即“仅ID记录:”)。

我需要分析/提取标题为“日期”,“时间”,“通道”,“标签ID”,“天线”和“功率”的列中的所有数据

enter image description here

r subset extract
2个回答
0
投票

由于您不知道需要跳过多少行,因此我们可以使用readLines来读取文件中的所有文本。使用grep文本'ID only records :'查找行号,然后通过将文本折叠成一个字符串开始从该行读取数据。

temp <- readLines('temp.txt')

output <- read.table(text = paste0(trimws(temp[(
                 grep('ID only records :', temp) + 1) : length(temp)]), 
                collapse = "\n"), header = TRUE)

0
投票

我们可以将grepsystem命令一起使用,以在skip中使用它,并通过read.table读取数据

read.table('temp.txt', skip =
      as.integer(system('grep -n Date temp.txt|cut -d: -f 1', intern = TRUE))-1,
                header = TRUE)
#      Date     Time Channel TagID Antenna Power
#1 02/17/20 12:57:50       1    61       1    90
#2 02/17/20 12:57:55       1    61       1    90
#3 02/17/20 12:58:00       1   999       2    55
#4 02/17/20 12:58:05       1   999       2    58
#5 02/17/20 12:58:10       1   999       2    57
#6 02/17/20 12:58:15       1    61       3    87
© www.soinside.com 2019 - 2024. All rights reserved.