You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R语言中合并CSV文件并将文件名设为列标题

Fixing Your CSV Merging Issue with R

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:

IDFile1File2
1AB
2AB
3AB
4AB

Why Your Original Code Didn't Work

  • bind_rows stacks all rows from every CSV into one long data frame, which is not what you need for horizontal merging.
  • Without specifying col_names, read_csv treats 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 19:52:29