Mark Davies
Mark Davies

Reputation: 940

Error when creating summary table with table1: "invalid model formula in ExtractVars"

I am using table1 package for first time. I am trying to create a summary table of descriptive statistics

This is my code

data <- read_excel("correct file path", 
                      skip= 1,) 


mydata <-  data[, -c(19:40)]
i <-  c(5:18)

mydata[, i] <- apply(mydata[, i],2, function(x) as.numeric(as.character(x))) 


mydata <-  na.omit(mydata)

table1::label(dat$Sex) <- "Sex"
table1::label(dat$Age) <- "Age"
table1::label(dat$SBP) <- "SBP"
table1::label(dat$DBP) <- "DBP"
table1::label(dat$BMI) <- "BMI"
table1::label(dat$WHR) <- "waist:Hip"
table1::label(dat$`LTM %`) <- "% Lean tissue mass"
table1::label(dat$`FM %`) <- "% Fat mass"

sumtab <- table1::table1(~Sex + Age + SBP + DBP + BMI + WHR + 'LTM %' + 'FM %' , data = dat) 

I get the following error

Error in terms.formula(formula, data = data) : 
  invalid model formula in ExtractVars

I cannot see what I've done wrong

Upvotes: 1

Views: 740

Answers (1)

akrun
akrun

Reputation: 886938

The issue is with single quotes ('), instead use backquotes

sumtab <- table1::table1(~Sex + Age + SBP + DBP + BMI +
            WHR + `LTM %` + `FM %` , data = dat) 

Using a reproducible example

library(table1)
 table1(~ sex + age + wt  + 'LTM %', data=dat)

Error in terms.formula(formula, data = data) : invalid model formula in ExtractVars

single quote results in error as in the OP's post

table1(~ sex + age + wt  + `LTM %`, data=dat) 

-output

enter image description here

data

set.seed(24)
dat <- expand.grid(id=1:10, sex=c("Male", "Female"), treat=c("Treated", "Placebo"))
dat$age <- runif(nrow(dat), 10, 50)
dat$age[3] <- NA  # Add a missing value
dat$wt <- exp(rnorm(nrow(dat), log(70), 0.2))
dat$`LTM %` <-  sample(40:50, nrow(dat), replace = TRUE)
label(dat$sex) <- "Sex"
label(dat$age) <- "Age"
label(dat$treat) <- "Treatment Group"
label(dat$wt) <- "Weight"
label(dat$`LTM %`) <- "% Lean tissue mass"

Upvotes: 1

Related Questions