我对R相对较新。我有一个数据集,该数据集已通过包xlsx导入到R中,并通过“ randomAssignment”列进行了过滤。但是,在新创建的数据帧(例如ABCD,CDEF等)中,存在带有空行的列;我要删除这些列。最好/最快的方法是什么?
require(xlsx)
require(tidyr)
require (dplyr)
require(tidyverse)
#IMPORT XLSX DATA INTO R USING XLSX PACKAGE
originalData <- read.xlsx("C:/Users/help/Desktop/GetTestedMessageTesting_FinalRawData_12292018.xlsx", 1, header = TRUE, colIndex = NULL, as.data.frame = TRUE)
ABCD <- filter (originalData, randomAssignment == "ABCD")
EFGH <- filter (originalData, randomAssignment == "EFGH")
IJKL <- filter (originalData, randomAssignment == "IJKL")
MNOP <- filter (originalData, randomAssignment == "MNOP")
QRST <- filter (originalData, randomAssignment == "QRST")
UVWX <- filter (originalData, randomAssignment == "UVWX")
CDEF <- filter (originalData, randomAssignment == "CDEF")
YZAB <- filter (originalData, randomAssignment == "YZAB")
答案 0 :(得分:0)
我解释了您的问题,以删除所有缺少/ NA值的列。这是一种解决方案-如果您的数据实际上不是NA
,则可能需要修改匿名函数。
该函数的要旨是,我们为my_mtcars
的每一列创建一个布尔值(TRUE / FALSE),该布尔值对应于所有条目是否都是NA
,我们将其否定以返回该值列。
#create copy of mtcars
my_mtcars <- mtcars
#set hp to NA
my_mtcars$hp <- NA
#filter out columns that are all NA
head(my_mtcars[, sapply(my_mtcars, function(x) !all(is.na(x)))])
#> mpg cyl disp drat wt qsec vs am gear carb
#> Mazda RX4 21.0 6 160 3.90 2.620 16.46 0 1 4 4
#> Mazda RX4 Wag 21.0 6 160 3.90 2.875 17.02 0 1 4 4
#> Datsun 710 22.8 4 108 3.85 2.320 18.61 1 1 4 1
#> Hornet 4 Drive 21.4 6 258 3.08 3.215 19.44 1 0 3 1
#> Hornet Sportabout 18.7 8 360 3.15 3.440 17.02 0 0 3 2
#> Valiant 18.1 6 225 2.76 3.460 20.22 1 0 3 1
由reprex package(v0.2.1)于2019-01-12创建