问题
I've been trying to run this code:
lm_model <- lm(Calories ~ Sodium + Carbohydrates + Protein + Caffeine + Dietary Fiber, 
               data = Starbucks)
but I keep getting
Error: unexpected symbol in "lm_model <- lm(Calories ~ Sodium + Carbohydrates + Protein + Caffeine + Dietary Fiber"
回答1:
You're getting that issue because the column name 'Dietary Fiber' is two words
To fix it, find out exactly what it's called in your data (e.g. run colnames(Starbucks)) and look for the column there and make sure you name it exactly the same
If the Dietary Fiber column name does indeed contain a space, you can surround it with the backtick character (i.e. ` ) so R knows to treat it as one single column name
Example
Here's an example of using lm() with a column whose names contain a space
a <- iris[1:10, c(1:2)]
# This works
lm(Sepal.Length ~ Sepal.Width, data = a)
# But what if we try the same thing with a space in the column name?
colnames(a)[2] <- "Sepal Width"
# Now it errors
lm(Sepal.Length ~ Sepal.Width, data = a)
# Error in eval(predvars, data, env) : object 'Sepal.Width' not found
# To use lm() function with a column name that contains spaces, use the backtick
lm(Sepal.Length ~ `Sepal Width`, data = a)
来源:https://stackoverflow.com/questions/65014051/unexpected-symbol-error-for-lm-model-addition