R语言dplyr包select函数报错:变量名含空格引发语法错误
Hey there! Let's break down why you're hitting that error and get your code working right away.
The Root Cause
The error Error: unexpected symbol in "file02 <- select(file01, Date, State, Market Center" pops up because you're using variable names with spaces (Market Center and Modal Price). R doesn't recognize space-separated text as a single variable name by default—when it hits the space after Market, it thinks you're starting a new, unconnected symbol, hence the "unexpected symbol" message.
Solution 1: Wrap Space-Separated Variables in Backticks
The quickest fix is to enclose any variable names with spaces in backticks `. This tells R to treat the entire text as one single variable. Your corrected code will look like this:
file02 <- select(file01, Date, State, `Market Center`, `Modal Price`)
Solution 2: Rename Variables to Avoid Spaces (Recommended)
If you want to skip dealing with backticks in future code, you can rename the variables first using dplyr::rename() to use underscores or camelCase instead of spaces:
# Rename variables to remove spaces file01 <- file01 %>% rename(Market_Center = `Market Center`, Modal_Price = `Modal Price`) # Now select the renamed variables without issues file02 <- select(file01, Date, State, Market_Center, Modal_Price)
A Quick Best Practice Tip
Sticking to variable names without spaces, special characters, or numbers at the start will save you from lots of syntax headaches in R. If you inherit a dataset with space-filled names, backticks are your reliable quick fix for immediate use.
内容的提问来源于stack exchange,提问作者Sankalp Mathur

