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
Because you have a data.table, you may use uniqueN and its na.rm argument:
data.table
uniqueN
na.rm
df[ , lapply(.SD, function(v) if(uniqueN(v, na.rm = TRUE) > 1) v)] # x # 1: 1 # 2: 2 # 3: 3 # 4: NA # 5: 5
A base alternative could be Filter(function(x) length(unique(x[!is.na(x)])) > 1, df)
base
Filter(function(x) length(unique(x[!is.na(x)])) > 1, df)