Remove constant columns with or without NAs

前端 未结 7 1605
深忆病人
深忆病人 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条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-17 18:25

    Here is an option:

    df[,which(df[,
           unlist(
            sapply(.SD,function(x) length(unique(x[!is.na(x)])) >1))]),
       with=FALSE]
    
        x
    1:  1
    2:  2
    3:  3
    4: NA
    5:  5
    

    For each column of the data.table we count the number of unique values different of NA. We keep only column that have more than one value.

提交回复
热议问题