Unexpected symbol error for lm_model addition [closed]

眉间皱痕 提交于 2021-01-20 13:33:05

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!