R新手求教:用fread/read_csv读取CSV时忽略46列后内容的方法
Hey there! As someone who’s wrestled with messy, quote-ridden CSVs in R before, I totally get how frustrating this error is. The good news is both fread (from data.table) and read_csv (from readr) have straightforward ways to force importing only the first 46 columns, ignoring any extra junk caused by unescaped quotes or commas in your comment fields.
Using fread (data.table)
fread has a handy select parameter that lets you specify exactly which columns to load. Since you know you need the first 46 columns, just pass the index range 1:46:
library(data.table) your_data <- fread("your_file.csv", select = 1:46)
This works because fread will only parse and keep the columns you specify—any extra text beyond column 46 gets discarded automatically, even if the parser detects it as additional columns. If you prefer using column names instead of indices (safer if columns ever reorder), you can list them out too:
# Example: List all column names up to "Team-B COMMENTS" col_names <- c("Col1", "Col2", ..., "Team-A COMMENTS", "Team-B COMMENTS") your_data <- fread("your_file.csv", select = col_names)
Using read_csv (readr)
For read_csv, use the col_select parameter (available in newer versions of readr) to pick the first 46 columns:
library(readr) your_data <- read_csv("your_file.csv", col_select = 1:46)
If you’re using an older version of readr where col_select isn’t available, you can use cols_only to define which columns to keep. For example:
# Keep all columns up to the 46th (replace with your actual column names/types if needed) your_data <- read_csv("your_file.csv", cols_only( Col1 = col_character(), Col2 = col_double(), # ... list all 46 columns, or use `col_guess()` for automatic type detection `Team-A COMMENTS` = col_character(), `Team-B COMMENTS` = col_character() ))
Bonus: Cleaning Up Comment Columns Later
Once your data is loaded, if you want to fix unescaped quotes in the comment columns, you can use functions from the stringr package to strip or escape them. For example:
library(stringr) your_data$`Team-A COMMENTS` <- str_replace_all(your_data$`Team-A COMMENTS`, '"', '')
内容的提问来源于stack exchange,提问作者SK_R_Beginner

