2016-10-19 42 views
0

我需要一個for循環R.「正常」循環公式裏面是R中非常簡單的(例如,見這裏https://www.r-bloggers.com/how-to-write-the-first-for-loop-in-r/),但因爲有「」我的公式中不出現工作......有沒有人知道解決這個問題的方法?在這個公式我想ID1是一個變量,而我有500點不同的IDR代表公式中環

testing <- formula(paste("STATUS ~ as.factor(data$TEMP) + C1 + ID1 * ID2 ")) 
+0

你想要所有的ID之間的所有雙向交互?如果是的話,你可以修改[this](http://stackoverflow.com/questions/11633403/how-to-automatically-include-all-2-way-interactions-in-a-glm-model-in-r)與'update()'函數。 – roman

+0

嗯有趣!是的,我希望那樣!你能幫忙一下嗎(我不是R專家)那會是什麼樣子? –

+0

我添加了一個答案,但讓我知道如果你需要更多的幫助 – roman

回答

0

使用as.formula而不僅僅是formula列表。這應該在paste上工作。雖然你的版本適用於我..我從formula這兩種方式。設置sep="",所以它不包括在公式中的任何更多的空間... 關於第二部分,我不知道你在問什麼。你也想要它作爲因素?

2
y <- rnorm(10) 
x1 <- rnorm(10) 
x2 <- rnorm(10) 
x3 <- rnorm(10) 
d <- data.frame(y, x1, x2, x3) 

# fit a model with all 2 way interactions 
model1 <- lm(y ~ .*., d) 
# remove one that you don't want 
model2 <- update(model1, ~.-x2:x3)