在R中未找到添加的列
我想在R中训练一个线性模型。因此,我想取一个解释变量的平均值。我使用以下代码将mean_of_price列添加到我的表中:在R中未找到添加的列,r,R,我想在R中训练一个线性模型。因此,我想取一个解释变量的平均值。我使用以下代码将mean_of_price列添加到我的表中: prices2 = subset(prices, type == "Apartment") prices2$mean_of_size = mean(prices2$size) prices2 如果我打印prices2,则可以看到\u price的mean\u列。但是,如果我用lm(price~type+mean\u of\u size+size)训练一
prices2 = subset(prices, type == "Apartment")
prices2$mean_of_size = mean(prices2$size)
prices2
如果我打印prices2,则可以看到\u price的mean\u列。但是,如果我用lm(price~type+mean\u of\u size+size)训练一个线性模型,data=prices2)
评估(预变量、数据、环境)中出错:找不到对象“平均大小”
这里有什么问题?可能是
的问题。
正如@akrun所说,)
没有任何帮助:
lm(price~type+mean_of_size+size), data = prices2)
应该是
lm(price~type+mean_of_size+size, data = prices2)
但也要注意
prices2$mean_of_size = mean(prices2$size)
正在为整个列指定相同的值。只是为了确定这就是你想要的
既然您说这就是您想要的,请注意,您的模型将无法以任何方式使用该信息。如果每行的每个值都相同,则其中没有信息,您可能会得到NA
简单的例子:
x<-rnorm(100) # 100 random values pulled from a normal distribution
y<-rnorm(100) # 100 random values pulled from a normal distribution
z<-rep(5,100) # the same value 100 times
summary(lm(y~x+z))
Call:
lm(formula = y ~ x + z)
Residuals:
Min 1Q Median 3Q Max
-2.44429 -0.71534 -0.07313 0.48823 2.44896
Coefficients: (1 not defined because of singularities)
Estimate Std. Error t value Pr(>|t|)
(Intercept) -0.1626 0.1027 -1.583 0.117
x 0.1636 0.1037 1.578 0.118
z NA NA NA NA
之所以如此,是因为)
在数据之前,即您可以尝试lm(price~type+mean\u of_size+size,data=prices2)
很抱歉,粘贴我的代码时出现了问题。我在data=prices2之后有一个“'),所以这不是问题。你可以尝试一个新的R会话吗?你可以在dput输出中显示dput(prices2)
或str(prices2)
,没有名为price
names(prices2)#[1]“size”类型“mean\u of\u size”的列
每行的相同值确实是我想要的
x<-rnorm(100) # 100 random values pulled from a normal distribution
y<-rnorm(100) # 100 random values pulled from a normal distribution
z<-rep(5,100) # the same value 100 times
summary(lm(y~x+z))
Call:
lm(formula = y ~ x + z)
Residuals:
Min 1Q Median 3Q Max
-2.44429 -0.71534 -0.07313 0.48823 2.44896
Coefficients: (1 not defined because of singularities)
Estimate Std. Error t value Pr(>|t|)
(Intercept) -0.1626 0.1027 -1.583 0.117
x 0.1636 0.1037 1.578 0.118
z NA NA NA NA