I am trying to get many lm models work in a function and I need to automatically drop constant columns from my data.table. Thus, I want to keep only columns wit
lm
If you really mean DROPing those columns, here is a solution:
library(data.table) dt <- data.table(x=c(1,2,3,NA,5), y=c(1,1,NA,NA,NA), z=c(NA,NA,NA,NA,NA), d=c(2,2,2,2,2)) for (col in names(copy(dt))){ v = var(dt[[col]], na.rm = TRUE) if (v == 0 | is.na(v)) dt[, (col) := NULL] }