How to include brackets as part of a string in a linear regression model formula?

75 Views Asked by At

I am currently looping through column headings in data frame imported from excel that contains brackets.

Example of what the data frame looks like:

df<-data.frame("ID"=c(233,233,243,243),
               "Treatment"=c("A1","B1","A1","B1"),
               "A(secs)"=c(0.1,0.2,0.2,0.1),
               "B(secs)"=c(0.4,0.5,2,1))

And i want to loop through the headings to run a random effects model as shown in the code below:

for (i in c("A(secs)","B(secs")){
 FF_df <- df %>%
    group_by(Treatment)%>%
    summarize(mean=mean(!!sym(i)),
              sem = sd(!!sym(i))/sqrt(n()),
              n = n(),
              max = mean + sem, min = mean - sem)

 formula <- as.formula(paste(i,"~ Treatment + (1| ID)")) 
      model<-lmer(formula,data=df)
      summary(model)
}

But i get the following error at the code line of "model<-lmer(formula,data=df)":

Error in A(secs) : could not find function "A"

I've tried backslash around A(secs) but then get this error at the for loop code:

Error in evalq({ : object 'A(secs)' not found
0

There are 0 best solutions below