R: Remove multiple empty columns of character variables

后端 未结 9 1238
轮回少年
轮回少年 2020-12-08 11:06

I have a data frame where all the variables are of character type. Many of the columns are completely empty, i.e. only the variable headers are there, but no values. Is ther

9条回答
  •  悲&欢浪女
    2020-12-08 11:39

    You can do either of the following:

    emptycols <- sapply(df, function (k) all(is.na(k)))
    df <- df[!emptycols]
    

    or:

    emptycols <- colSums(is.na(df)) == nrow(df)
    df <- df[!emptycols]
    

    If by empty you mean they are "", the second approach can be adapted like so:

    emptycols <- colSums(df == "") == nrow(df)
    

提交回复
热议问题