2014-04-04 42 views
0

我有以下代码包括平方预测模型矩阵

x <- c(1, 2, 3) 
y <- c(2, 3, 4) 
z <- c(3, 4, 5) 
df <- data.frame(x, y, z) 

model.matrix(x ~ .^4, df) 

这让我预测$ Y,Z $和$ Y的模型矩阵:Z $。不过,我也想要y^2和z^2,并且想要使用一个使用“$。$”的解决方案,因为我有很多其他的预测变量超出$ y $和$ z $。什么是最好的方法来解决这个问题?

回答

1

试试这个:

> x <- c(1, 2, 3) 
> y <- c(2, 3, 4) 
> z <- c(3, 4, 5) 
> df <- data.frame(x, y, z) 
> 
> #Assuming that your 1st column is the response variable, then I excluded it to have 
> #just the independent variables as a new data.frame called df.2 
> df.2=df[,-1] 
> model.matrix(x ~ .^4+I(df.2^2), df) 
    (Intercept) y z I(df.2^2)y I(df.2^2)z y:z 
1   1 2 3   4   9 6 
2   1 3 4   9   16 12 
3   1 4 5   16   25 20 
attr(,"assign") 
[1] 0 1 2 3 3 4 
+0

谢谢你 - 这是完美的! – encircled