CSV导入列名未拆分及末列丢失问题:无需Excel手动处理的快速修复
I’ve run into this exact issue before with barttorvik’s CSV exports—here’s a quick, code-based fix that avoids manually editing the file in Excel every time:
Method 1: Explicitly Correct Column Names
The core problem is the header line incorrectly merges "Fun RK" and "adjt" into a single column name (Fun RK, adjt), giving us 44 column names but 45 data columns. We can fix this by rebuilding the header programmatically:
library(readr) # Define the CSV URL url <- "http://barttorvik.com/2021_team_results.csv" # Step 1: Pull the original header line raw_header <- read_lines(url, n_max = 1) # Step 2: Split the header into individual column names header_split <- strsplit(raw_header, ",")[[1]] # Step 3: Fix the merged column entry merged_col_pos <- which(grepl("Fun RK", header_split)) fixed_header <- c( header_split[1:(merged_col_pos - 1)], "Fun RK", "adjt", header_split[(merged_col_pos + 1):length(header_split)] ) # Step 4: Read the CSV with our corrected header (skip the original bad header) data <- read_csv(url, skip = 1, col_names = fixed_header)
Method 2: Quick Text Replacement (Concise Version)
If you want a shorter one-liner-style fix, you can read the entire CSV as text, patch the header line, then parse it:
library(readr) url <- "http://barttorvik.com/2021_team_results.csv" # Read all lines of the CSV csv_text <- read_lines(url) # Replace the merged column name with two separate entries csv_text[1] <- gsub("Fun RK, adjt", "Fun RK,adjt", csv_text[1]) # Parse the corrected text as a CSV data <- read_csv(I(csv_text))
Both methods will correctly parse all 45 columns without any manual file edits. The first approach is more explicit if you ever need to adjust other column names later, while the second is a fast, straightforward fix for this specific issue.
内容的提问来源于stack exchange,提问作者Brian

