请求R代码:批量读取文件夹中多列TXT文件并拆分保存为三类文件
Got it, let's tackle this problem step by step. Here's a robust R solution that works for any number of your TXT files (whether it's 4 or more) and neatly combines the corresponding columns across all files.
Step-by-Step Explanation & Code
First, we'll grab all your target files, read each one to extract the three columns, merge the data by measurement row, then save the results as three separate TXT files.
# 1. Set your working directory to where your TXT files are stored # Replace the path below with your actual folder path setwd("C:/your/folder/path") # 2. Get all TXT files matching the "fileX.txt" naming pattern file_list <- list.files(pattern = "^file\\d+\\.txt$") # 3. Initialize empty lists to store each column's data from all files day_records <- list() temp_records <- list() press_records <- list() # 4. Loop through each file to extract data for (file_name in file_list) { # Read the file - adjust 'sep' if your data uses commas, spaces, etc. # Use header=TRUE if your files have column headers (like "day", "temperature") raw_data <- read.table(file_name, header = FALSE, sep = "\t") # Extract each column (assuming columns 1=day, 2=temperature, 3=pressure) day_records[[file_name]] <- raw_data[, 1] temp_records[[file_name]] <- raw_data[, 2] press_records[[file_name]] <- raw_data[, 3] } # 5. Combine all records into data frames (each row = same measurement across files) combined_days <- do.call(cbind, day_records) combined_temps <- do.call(cbind, temp_records) combined_pressures <- do.call(cbind, press_records) # 6. Add meaningful column names (remove .txt extension from file names) colnames(combined_days) <- gsub("\\.txt$", "", file_list) colnames(combined_temps) <- gsub("\\.txt$", "", file_list) colnames(combined_pressures) <- gsub("\\.txt$", "", file_list) # 7. Save the combined data to three separate TXT files write.table(combined_days, "combined_day_data.txt", sep = "\t", row.names = FALSE, quote = FALSE) write.table(combined_temps, "combined_temperature_data.txt", sep = "\t", row.names = FALSE, quote = FALSE) write.table(combined_pressures, "combined_pressure_data.txt", sep = "\t", row.names = FALSE, quote = FALSE)
Key Notes to Adjust for Your Data
- Separator: If your data uses spaces instead of tabs, change
sep = "\t"tosep = " "(or usesep = ","for CSV-style files). - Headers: If your input files have column headers (e.g., first line is "day", "temperature", "pressure"), set
header = TRUEinread.table, and you can extract columns by name instead of index (e.g.,raw_data$dayinstead ofraw_data[,1]). - Row Consistency: This code assumes all files have the same number of measurement rows. If some files have missing rows, you can use
dplyr::bind_colswithtidyr::fillto handle gaps, but that's an extra step if needed.
内容的提问来源于stack exchange,提问作者AstroCab
相关产品推荐
相关产品推荐

