【问题标题】:Filtering process not fetching full data? Using dplyr filter and grep过滤过程未获取完整数据?使用 dplyr 过滤器和 grep
【发布时间】:2019-05-20 08:56:50
【问题描述】:

我有这个日志文件,每行大约有 1200 个字符(最多)。我想要做的是先阅读这个,然后将文件的某些部分提取到新列中。我想提取包含文本“[DF_API: input string]”的行。 当我阅读它然后根据我感兴趣的行进行过滤时,似乎我正在丢失数据。我使用 dplyr 过滤器并使用标准 grep 进行了尝试,结果相同。

不知道为什么会这样。感谢您对此的帮助。代码和数据在以下链接中。 萨蒂什

代码如下

library(dplyr)
setwd("C:/Users/satis/Documents/VF/df_issue_dec01")

sec1 <- read.delim(file="secondary1_aa_small.log")
head(sec1)
names(sec1) <- c("V1")
sec1_test <- filter(sec1,str_detect(V1,"DF_API: input string")==TRUE)
head(sec1_test)

sec1_test2 = sec1[grep("DF_API: input string",sec1$V1, perl = TRUE),]
head(sec1_test2)

write.csv(sec1_test, file = "test_out.txt", row.names = F, quote = F)
write.csv(sec1_test2, file = "test2_out.txt", row.names = F, quote = F)

数据(和代码)在下面的链接中给出。抱歉,我应该使用 dput。

https://spaces.hightail.com/space/arJlYkgIev

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    试试下面的代码,它可以根据匹配条件为您提供文件中过滤行的数据框。

    #to read your file
    sec1 <- readLines("secondary1_aa_small.log")
    #framing a dataframe by extracting required lines from above file
    new_sec1 <- data.frame(grep("DF_API: input string", sec1, value = T))
    names(new_sec1) <- c("V1")
    

    编辑:将上述列拆分为多列的简单方法

    #extracting substring in between < & >
    new_sec1$V1 <- gsub(".*[<\t]([^>]+)[>].*", "\\1", new_sec1$V1)
    #replacing comma(,) with a white space
    new_sec1$V1 <- gsub("[,]+", " ", new_sec1$V1)
    #splitting into separate columns
    new_sec1 <-  strsplit(new_sec1$V1, " ")
    new_sec1 <-  lapply(new_sec1, function(x) x[x != ""] )
    new_sec1 <-  do.call(rbind, new_sec1)
    new_sec1 <- data.frame(new_sec1)
    

    为您的分析更改列名称。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-14
      • 2014-09-10
      相关资源
      最近更新 更多