使用dplyr管道移除空列 [英] Piping the removal of empty columns using dplyr

查看:35
本文介绍了使用dplyr管道移除空列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个广泛格式的参与者问卷调查数据框架,每一列代表一个特定的问题/项目.

I have a data frame of participant questionnaire responses in wide format, with each column representing a particular question/item.

数据框看起来像这样:

id <- c(1, 2, 3, 4)
Q1 <- c(NA, NA, NA, NA)
Q2 <- c(1, "", 4, 5)
Q3 <- c(NA, 2, 3, 4)
Q4 <- c("", "", 2, 2)
Q5 <- c("", "", "", "")
df <- data.frame(id, Q1, Q2, Q3, Q4, Q5)

我希望R删除在其每一行中具有(1)NA或(2)空白的所有值的列.因此,我不希望列Q1(它完全由NA组成)和列Q5(它完全由"形式的空白组成).

I want R to remove columns that has all values in each of its rows that are either (1) NA or (2) blanks. Therefore, I do not want column Q1 (which comprises entirely of NAs) and column Q5 (which comprises entirely of blanks in the form of "").

根据此线程,我是能够使用以下内容删除全部包含NA的列:

According to this thread, I am able to use the following to remove columns that comprise entirely of NAs:

df[, !apply(is.na(df), 2, all]

但是,该解决方案不能解决空格(").当我在dplyr管道中执行所有这些操作时,有人可以解释一下如何将上述代码合并到dplyr管道中吗?

However, that solution does not address blanks (""). As I am doing all of this in a dplyr pipe, could someone also explain how I could incorporate the above code into a dplyr pipe?

此刻,我的dplyr管道如下所示:

At this moment, my dplyr pipe looks like the following:

df <- df %>%
    select(relevant columns that I need)

此后,我被困在这里,并使用方括号[]来对非NA列进行子集化.

After which, I'm stuck here and am using the brackets [] to subset the non-NA columns.

谢谢!非常感谢.

推荐答案

我们可以使用 select_if

library(dplyr)
df %>%
   select_if(function(x) !(all(is.na(x)) | all(x=="")))

#  id Q2 Q3 Q4
#1  1  1 NA   
#2  2     2   
#3  3  4  3  2
#4  4  5  4  2

或者不使用匿名函数调用

Or without using an anonymous function call

df %>% select_if(~!(all(is.na(.)) | all(. == "")))


您还可以将 apply 语句修改为

df[!apply(df, 2, function(x) all(is.na(x)) | all(x==""))]

或使用 colSums

df[colSums(is.na(df) | df == "") != nrow(df)]

和逆

df[colSums(!(is.na(df) | df == "")) > 0]

这篇关于使用dplyr管道移除空列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆