【问题标题】:Extracting specific rows from each text files and store in one txt file从每个文本文件中提取特定行并存储在一个 txt 文件中
【发布时间】:2020-12-02 03:51:15
【问题描述】:
   ListOfFileNames= list.files(path = "D:/in/",
                       pattern = '*.txt',recursive = T)
   options(stringsAsFactors = F)
   setwd("D:/in/")
   outFile <- file("output.txt", "w")
   for (i in ListOfFileNames){
     x = read.delim(ListOfFileNames[i], skip = 29, nrows= 1)
     x = as.character(x)
    writeLines(x, paste('D:/out/out.csv',sep = ","))

   }

enter link description hereThis the txt files that I have.

我想从每个 txt 文件中提取第 30 行和第 63 行并将其保存到一个 txt 文件中。我如何在 R 中解决这个问题?这是我尝试提取第 30 行并将其存储在一个 csv 文件中的代码。但它不起作用。你能帮忙吗?

谢谢

【问题讨论】:

  • 共享两个文件并向我们展示您迄今为止尝试过的代码。如果它是机密的,请根据您的需要进行更改,否则这里的任何人都无法帮助您。
  • 好的,我上传两个文件。
  • 你需要这个权利 "C2,2020-03-13,10:00:00,136.99" 和 "C2,2020-03-14,19:00:00,133.14"。文件名 03_19_C2.txt
  • 是的,正确。来自另一个 txt 文件的相同行数。

标签: r extract rows


【解决方案1】:

你可以试试:

ListOfFileNames= list.files(path = "D:/in/",
                       pattern = '*.txt',recursive = TRUE, full.names = TRUE)

result <- do.call(rbind, lapply(ListOfFileNames, function(x) 
                  read.csv(x)[c(30, 63), ]))

write.csv(result, 'D:/out/out.csv', row.names = FALSE)

【讨论】:

  • 谢谢你,但它给了我很多文件。我只想得到一个文件。
  • @KayKhaingKyaw 查看更新后的答案,最后只获得一个组合文件。
最近更新 更多