删除xts中的NA列

lab*_*tes 6 r xts quantmod

我有以下格式的xts

                   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  ......
Run Code Online (Sandbox Code Playgroud)

是否有一个函数可以应用于生成新的xts或data.frame缺少仅包含NA的列?

带有NA的列的位置不是静态的,因此无法按名称或位置删除这些列

Jil*_*ina 5

Supose DF是您的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
Run Code Online (Sandbox Code Playgroud)


Jos*_*ich 5

@Jiber解决方案有效,但如果没有包含所有NA. 例如:

# 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
Run Code Online (Sandbox Code Playgroud)

这是一个无论是否存在包含所有缺失值的列都有效的解决方案:

y <- x[,apply(!is.na(x), 2, all)]
x$High <- NA
x$Close <- NA
z <- x[,apply(!is.na(x), 2, all)]
Run Code Online (Sandbox Code Playgroud)