Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
720 views
in Technique[技术] by (71.8m points)

r - Repeat regression with varying dependent variable

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
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...