Remove constant columns with or without NAs

前端 未结 7 1606
深忆病人
深忆病人 2021-01-17 17:30

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

7条回答
  •  猫巷女王i
    2021-01-17 18:06

    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]
    }
    

提交回复
热议问题