如何通过R语言read.delim()读取txt文件时保留复杂列名原符号?
read.delim() Absolutely! You don’t have to convert your .txt file to Excel to retain those special characters in your column headers—read.delim() has a simple built-in fix for this.
By default, read.delim() (which inherits behavior from read.table()) uses check.names = TRUE, which automatically replaces any characters that aren’t letters, numbers, or dots with dots. This is why your spaces, +, -, and other symbols get converted.
To preserve the original column names exactly as they appear in your .txt file, just set check.names = FALSE when calling the function:
# Read the text file with all special characters in column names preserved your_data <- read.delim("your_file_path.txt", check.names = FALSE)
This will keep every character in your column headers intact—spaces, /, +, -, |, and all. The result will match what you get when using readxl::read_excel() on an Excel version of the file.
A quick note for working with these column names later: since they contain special characters, you’ll need to wrap them in backticks if you reference them directly with the $ operator, or use double brackets:
# Example of accessing the tricky column name your_data$`Basket/Fruit/Many Apples/Pears+ Cherries-/Seeds+ Peel-| Freq. (%)` # Or using double brackets your_data[["Basket/Fruit/Many Apples/Pears+ Cherries-/Seeds+ Peel-| Freq. (%)"]]
内容的提问来源于stack exchange,提问作者lostnewbiecoder

