Olympia
Olympia

Reputation: 537

How do I paste a column from a R dataframe in a loop for a formula using the $?

I need help pasting a data frame column as a formula in R using the $ sign.

df1 <- data.frame(id1 = c(1, 2, 3, 4, 5),
              id2 = c(1, 2, 3, 4, 5),
              var1 = c(3,6,6,9,5),
              var2 = c(1, 1, 0, 0, 1))
rownames(df1)<-c("first","second","third","fourth","fifth")

trait=c("id1","id2")
list=as.character("var1","var2")

for(i in trait){
  fit <- lm(df1[,i]~df1$list[2])
}

I want to paste the second part of the lm (df1$list[2]). After the $, I want that it pastes the corresponding element of the character vector list.

Upvotes: 0

Views: 682

Answers (2)

Olympia
Olympia

Reputation: 537

The answer that worked best for me was that of MrFlick above:

for(i in seq_along(trait)) {
fit <- lm(reformulate(list[i], trait[i]), df1); print(fit)}

Upvotes: 0

G. Grothendieck
G. Grothendieck

Reputation: 269441

lm can run multiple left hand sides at once:

lm(cbind(id1, id2) ~ var1 + var2, f1)

giving:

Call:
lm(formula = cbind(id1, id2) ~ var1 + var2, data = f1)

Coefficients:
             id1      id2    
(Intercept)  0.09091  0.09091
var1         0.45455  0.45455
var2         0.45455  0.45455

Upvotes: 1

Related Questions