在 sparklyr 中删除 NA 列

Delete NA Columns in sparklyr

我有一个包含 75 列的数据框,其中 12 列全部为 NA,一些列为 70% NA。我想删除具有 >=70% NA 的列。

谁能帮我解决这个问题?我试过了

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

但我遇到异常:

Error: Unable to retreive a spark_connection from object of class NULL

我也试过:

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

df[, colSums(is.na(df)) < nrow(df)]

但我遇到了异常,因为

Error in colSums(!is.na(df)) : 'x' must be an array of at least two dimensions

sparklyr中似乎有点棘手,但是,我们可以从数据集的本地副本中获取需要删除的列的索引,并使用select删除这些列

j1 <- which(!colSums(!is.na(df)))
library(sparklyr)
sc <- spark_connect(master = "local")
df_tbl <- copy_to(sc, df)
library(dplyr)
df_tbl %>% 
         select(-j1)
# Source:   query [20 x 2]
#Database: spark connection master=local[4] app=sparklyr #local=TRUE

#    col2        col3
#   <int>       <dbl>
#1      1 -1.31690812
#2      1  0.59826911
#3      4 -0.76221437
#4      3 -1.42909030
#5      3  0.33224445
#6      5 -0.46906069
#7      1 -0.33498679
#8      4  1.53625216
#9      4  0.60999453
#10     1  0.51633570
#11     3 -0.07430856
#12     2 -0.60515695
#13     4 -1.70964518
#14     4 -0.26869311
#15     1 -0.64859151
#16     5 -0.09411013
#17     1 -0.08554095
#18    NA  0.11953107
#19     3 -0.11629639
#20    NA -0.94382724

数据

set.seed(24)
df <- data.frame(col1 = NA_real_, col2 = sample(c(NA, 1:5), 20, 
               replace = TRUE), col3 = rnorm(20))