我有一个包含统计数据的文本文件。它们中的每一个都在单独的行上。我遍历R中的每一行并对其进行grep。我感兴趣的统计数据类型如下:
system.l2.precompression_table.entry_0_all_mappings 0 # all mappings for entry #0
system.l2.precompression_table.entry_0_avg_mappings 0 # average number of mappings for entry #0
system.l2.precompression_table.entry_10_all_mappings 30 # all mappings for entry #10
system.l2.precompression_table.entry_10_avg_mappings 4 # average number of mappings for entry #10条目的编号从0开始,直到63。
在其他情况下,当我试图收集没有特定模式的统计数据时,我会这样做。
if (grepl("final_tick", line))
{
matches <- regmatches(line, gregexpr("[[:digit:]]+\\.*[[:digit:]]*", line))
final_tick = as.numeric(unlist(matches))[1]
}我想做一些类似的事情,但不是像统计数据一样多的if语句。我想要有一个grep语句,它使用正则表达式来查找类似于"entry_num_###_mappings“的统计数据,并将其保存到一个数据框中,其中一列具有该统计数据的名称,而另一列具有数值。(正则表达式可以捕获以entry开头并以映射结束的任何统计数据。映射的类型(all/avg)可以改变)。
大概是这样的:
df
stat | value
entry_10_all_mappings 30
entry_10_avg_mappings 4发布于 2019-09-13 05:40:25
使用stringr包,您可以执行以下操作:
library(stringr)
# Select any line containing "entry_num_all_mappings" or "entry_num_avg_mappings":
selection <- readLines("data.txt") %>%
str_subset("entry_\\d+_a.._mappings")
# Extract the "stat" part
stat <- selection %>%
str_extract("entry_\\d+_a.._mappings")
# Extract the "value" part
value <- selection %>%
str_extract(" \\d+ ") %>%
trimws()
# Create your data frame
df <- data.frame(stat, value)发布于 2019-09-13 08:16:02
您可以在数据帧中使用read.table读取文本文件
df <- read.table("name_of_text_file.txt")选择符合所需模式的所有行
df1 <- df[grepl("entry_\\d+_(avg|all)_mappings", df$V1), ]使用模式创建新列(如果需要
df1$V3 <- sub(".*(entry_\\d+_(avg|all)_mapping)", "\\1", df1$V1)https://stackoverflow.com/questions/57914366
复制相似问题