问题
I have an xts in the following format
a b c d e f ......
2011-01-03 11.40 NA 23.12 0.23 123.11 NA ......
2011-01-04 11.49 NA 23.15 1.11 111.11 NA ......
2011-01-05 NA NA 23.11 1.23 142.32 NA ......
2011-01-06 11.64 NA 39.01 NA 124.21 NA ......
2011-01-07 13.84 NA 12.12 1.53 152.12 NA ......
Is there a function I can apply to generate a new xts or data.frame missing the columns containing only NA?
The position of the columns with the NAs isn't static so just removing those columns by name or position isn't possible
回答1:
Supose DF
is your data.frame
DF [, -which(sapply(DF, function(x) sum(is.na(x)))==nrow(DF))]
a c d e
2011-01-03 11.40 23.12 0.23 123.11
2011-01-04 11.49 23.15 1.11 111.11
2011-01-05 NA 23.11 1.23 142.32
2011-01-06 11.64 39.01 NA 124.21
2011-01-07 13.84 12.12 1.53 152.12
回答2:
@Jiber's solution works, but might give you unexpected results if there are no columns with all NA
. For example:
# sample data
library(xts)
data(sample_matrix)
x <- as.xts(sample_matrix)
# Jiber's solution, when no columns have all missing values
DF <- as.data.frame(x)
DF[, -which(sapply(DF, function(x) sum(is.na(x)))==nrow(DF))]
# data frame with 0 columns and 180 rows
Here's a solution that works whether or not there are columns that have all missing values:
y <- x[,apply(!is.na(x), 2, all)]
x$High <- NA
x$Close <- NA
z <- x[,apply(!is.na(x), 2, all)]
回答3:
Try this:
dataframe[,-which(apply(is.na(dataframe), 2, all))]
回答4:
This seems simpler:
DF[, colSums(is.na(DF)) < nrow(DF)]
来源:https://stackoverflow.com/questions/13098888/removing-na-columns-in-xts