问题
I've searched both Stack and google for a solution, none found to solve my problem.
I have about 40 dependent variables, for which I aim to obtain adjusted means (lsmeans). I need adjusted means for group A and group B, after accounting for some covariates. My final object should be a data frame with predicted means for all 40 dependent variables for group A and group B.
This is what I tried, without any success:
# Examplified here with 2 outcome variables
outcome1 <- c(2, 4, 6, 8, 10, 12, 14, 16)
outcome2 <- c(1, 2, 3, 4, 5, 6, 7, 8)
var1 <- c("a", "a", "a", "a", "b", "b", "b", "b")
var2 <- c(10, 11, 12, 9, 14, 9, 5, 8)
var3 <- c(100, 101, 120, 90, 140, 90, 50, 80)
df <- data.frame(outcome1, outcome2, var1, var2, var3)
dependents <- c(outcome1, outcome2)
library(lsmeans) #install.packages("lsmeans")
results <- list()
for (i in seq_along(dependents) {
fit <- lm(i ~ var1 + var2 + var3, data= df)
summary <- summary(lsmeans(fit, "var1"))
summary$outcome <- i
results[i] <- summary
}
回答1:
There were a few typos and things, but I think this is what you want:
# Examplified here with 2 outcome variables
outcome1 <- c(2, 4, 6, 8, 10, 12, 14, 16)
outcome2 <- c(1, 2, 3, 4, 5, 6, 7, 8)
var1 <- c("a", "a", "a", "a", "b", "b", "b", "b")
var2 <- c(10, 11, 12, 9, 14, 9, 5, 8)
var3 <- c(100, 101, 120, 90, 140, 90, 50, 80)
df <- data.frame(outcome1, outcome2, var1, var2, var3)
dependents <- c("outcome1", "outcome2")
library(lsmeans) #install.packages("lsmeans")
results <- list()
for (i in seq_along(dependents)) {
eq <- paste(dependents[i],"~ var1 + var2 + var3")
fit <- lm(as.formula(eq), data= df)
summary <- summary(lsmeans(fit, "var1"))
summary$outcome <- i
results[[i]] <- summary
}
回答2:
Here is another option using lapply
.
dependents <- c('outcome1', 'outcome2')
lst <- lapply(dependents, function(x) {
fit <- lm(paste(x,'~', 'var1+var2+var3'), data=df)
summary(lsmeans(fit, 'var1', data=df))})
Map(cbind, lst, outcome = seq_along(dependents))
来源:https://stackoverflow.com/questions/31377737/repeat-regression-with-varying-dependent-variable