代码之家  ›  专栏  ›  技术社区  ›  Knowledge Seeker

读取、子集“选择”并在R中写入TXT文件

r
  •  0
  • Knowledge Seeker  · 技术社区  · 6 年前

    我想从中选一些 file1.txt 把它保存在另一个名为 file2.txt . 文件1.txt:

    abc 1 6 a
    abc 2 7 b
    efg 3 8 c
    abc 4 9 d
    efg 5 10 e
    

    我要在此处应用的数据库查询是( 不特定于语法 ):

    file2.txt <- select col2, col3, col4 from file1.txt where col1=abc
    

    文件2.txt:

    1 6 a
    2 7 b
    4 9 d
    

    是否有任何方法可以将R中的数据库类型查询应用于文本文件?我知道我们可以使用 grep() 功能。但是我找不到任何在线帮助?有人知道我如何解决我的问题吗?事先谢谢:) 请不要将此问题标记为重复:

    Searching for string within a text file in R

    这个问题有些不同。而且我不能用 sqldf 因为这个包不适用于.txt文件。

    3 回复  |  直到 6 年前
        1
  •  1
  •   G. Grothendieck    6 年前

    假设文件在末尾的注释中重复创建:

    library(sqldf)
    
    read.csv.sql("File1.txt", 
      "select V2, V3, V4 from file where V1 = 'abc'", header = FALSE, sep = " ")
    

    给:

      V2 V3 V4
    1  1  6  a
    2  2  7  b
    3  4  9  d
    

    注释

    Lines <- "abc 1 6 a
    abc 2 7 b
    efg 3 8 c
    abc 4 9 d
    efg 5 10 e
    "
    cat(Lines, file = "File1.txt")
    
        2
  •  1
  •   MSW Data    6 年前

    下面有助于回答来自csvfile的子集数据吗?

    library(sqldf);
    read.csv.sql(file, sql = "select * from file", header = TRUE, sep = ",")
    

    说明 用SQL语句将文件读取到r中并对其进行筛选。只有过滤部分由R处理,所以 可以容纳大于r所能处理的文件。

        3
  •  1
  •   hannes101    6 年前

    这应该是所有需要的,记住 like() 来自 data.table 程序包使用 grepl 在内部,所以我认为regex可能也是一个选项。

    library(data.table)
    # Depending on the characteristics of the csv file this call has to be adjusted
    dt <- data.table(read.csv("File1.txt", header = FALSE, sep = " "))
    # or
    dt <- fread("test.txt")
    # data.table looks like this after import
    dt <- structure(list(V1 = structure(c(1L, 1L, 2L, 1L, 2L)
          , .Label = c("abc", "efg")
          , class = "factor")
          , V2 = 1:5
          , V3 = 6:10
          , V4 = structure(1:5, .Label = c("a", "b", "c", "d", "e")
          , class = "factor")), row.names = c(NA, -5L)
          , class = c("data.table", "data.frame"))
    
    write.csv(dt[like(V1, "abc"), .(V2
                          , V3
                          , V4
                          )],file = "File2.txt", row.names = FALSE)