如何在R语言中合并CSV文件并将文件名设为列标题
Hey there! Let's get this sorted out for you. The main issues with your current code are twofold: you're using bind_rows (which stacks rows vertically instead of merging columns horizontally) and you aren't telling read_csv to skip treating the first row as headers. Here's a step-by-step solution tailored to your needs:
Step 1: Load Required Packages
We'll use readr for reading CSVs, dplyr for data manipulation, and purrr for working with lists of data frames:
library(readr) library(dplyr) library(purrr)
Step 2: Prepare File Paths and Names
First, grab the list of CSV files, and clean up their names to use as column headers (removing the .csv suffix):
# Get full paths to all CSV files file_paths <- list.files(pattern = "*.csv", full.names = TRUE) # Extract clean file names (without .csv) for column headers file_names <- gsub("\\.csv$", "", list.files(pattern = "*.csv"))
Step 3: Read Files with Correct Column Names
Instead of letting read_csv guess headers, we'll explicitly name the first column ID and the second column using the cleaned file name:
# Read each CSV and assign custom column names data_list <- map2(file_paths, file_names, function(path, name) { read_csv(path, col_names = c("ID", name), col_types = cols()) # col_types = cols() suppresses readr's guessing messages, optional but helpful for large datasets })
Step 4: Merge All Data Frames Horizontally
Use reduce to merge all data frames in the list by the ID column. Since you mentioned all files have identical first columns, inner_join will work perfectly (or full_join if you want to handle any accidental missing IDs):
combined_data <- reduce(data_list, inner_join, by = "ID")
Step 5: Check the Result
Now combined_data will have exactly the format you want:
- First column:
ID - Subsequent columns: Named after each CSV file, containing the second column data from each file
Example Output (Matching Your Sample)
For your File1.csv and File2.csv, the result will look like:
| ID | File1 | File2 |
|---|---|---|
| 1 | A | B |
| 2 | A | B |
| 3 | A | B |
| 4 | A | B |
Why Your Original Code Didn't Work
bind_rowsstacks all rows from every CSV into one long data frame, which is not what you need for horizontal merging.- Without specifying
col_names,read_csvtreats the first row of your first CSV as column headers, leading to the messy output you saw.
This approach will handle all 600 of your files automatically, no manual header editing required!
内容的提问来源于stack exchange,提问作者JanieDoe12

