【问题标题】:Extracting certain columns from multiple txt files and saving as new csv files?从多个 txt 文件中提取某些列并保存为新的 csv 文件?
【发布时间】:2019-08-23 00:35:24
【问题描述】:

我有大约 100 个 txt 文件。我正在尝试从每个文件中提取某些列,然后将其保存为每个 txt 文件的新 csv 文件。另外,我想将名称设置为“(原始 txt 文件的名称)_new.txt”之类的名称。

到目前为止,我已经能够一次读取所有文件,但我不确定如何从这里开始。任何帮助将不胜感激。

data_all=list.files(pattern='.*.txt')
data<-lapply(data_all,read.csv,header=TRUE,sep='\t',skip=9)

【问题讨论】:

  • 哪些是“某些”列?它是固定的列号,如第 1 列吗?第二个对于每个 txt 文件,或者您想按名称提取它们,例如每个名为“abc”和“xyz”的列?

标签: r


【解决方案1】:

也许你可以使用fread

library(data.table)
data_all=list.files(pattern='.*.txt')

read.certain <- function(x, certain= certain_cols){fread(x), select = certain}
dat <- lapply(data_all,read.certain)

【讨论】:

  • 能否添加如何将结果写入单个文件?
【解决方案2】:

我会这样做的。

# Merge all CSV files into a single dataframe
# Set the directory
setwd("C:/Users/rshuell/Desktop/input_files")

# Get a list of all the files in the directory
file_list <- list.files()

# Start merging the files in the directory into a single dataframe
for (file in file_list){
  # if the merged dataset doesn't exist, create it
  if (!exists("dataset")){
    dataset <- read.table(file, header=TRUE, sep="\t")
  }
  # if the merged dataset does exist, append to it
  if (exists("dataset")){
    temp_dataset <-read.table(file, header=TRUE, sep="\t")
    dataset<-rbind(dataset, temp_dataset)
    rm(temp_dataset)
  }
}

然后,选择你想要的列。

库(dplyr)

df1 %>%
  select(X, Y, Z)

Or ....

select(df1, X, Y, Z)

最后,将数据框保存到 CSV 文件中。

write.csv(df,'C:\\your_path\\new_file.csv')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-15
    • 1970-01-01
    • 2019-09-04
    • 1970-01-01
    • 2020-08-01
    • 2018-11-17
    • 2022-01-14
    相关资源
    最近更新 更多