Drop Columns with NA Values from xts Time Series in R (2 Examples)
In this R programming tutorial you’ll learn how to drop NA variables from an xts time series object.
Preparing the Examples
install.packages("xts") # Install & load xts library("xts") |
install.packages("xts") # Install & load xts library("xts")
my_xts <- xts(data.frame(col1 = 11:14, # Create xts time series object col2 = NA, col3 = c(3:1, NA)), as.Date(c("2024-03-11", "2016-07-12", "2022-11-13", "2022-11-26"))) my_xts # col1 col2 col3 # 2016-07-12 12 NA 2 # 2022-11-13 13 NA 1 # 2022-11-26 14 NA NA # 2024-03-11 11 NA 3 |
my_xts <- xts(data.frame(col1 = 11:14, # Create xts time series object col2 = NA, col3 = c(3:1, NA)), as.Date(c("2024-03-11", "2016-07-12", "2022-11-13", "2022-11-26"))) my_xts # col1 col2 col3 # 2016-07-12 12 NA 2 # 2022-11-13 13 NA 1 # 2022-11-26 14 NA NA # 2024-03-11 11 NA 3
Example 1: Delete Variables of xts Object Containing One or More NA Value
xts_one_NA <- my_xts[ , colSums(is.na(my_xts)) == 0] # Drop NA columns xts_one_NA # col1 # 2016-07-12 12 # 2022-11-13 13 # 2022-11-26 14 # 2024-03-11 11 |
xts_one_NA <- my_xts[ , colSums(is.na(my_xts)) == 0] # Drop NA columns xts_one_NA # col1 # 2016-07-12 12 # 2022-11-13 13 # 2022-11-26 14 # 2024-03-11 11
Example 2: Delete Variables of xts Object Containing Only NA Values
xts_all_NA <- my_xts[ , colSums(is.na(my_xts)) != nrow(my_xts)] # Drop all-NA columns xts_all_NA # col1 col3 # 2016-07-12 12 2 # 2022-11-13 13 1 # 2022-11-26 14 NA # 2024-03-11 11 3 |
xts_all_NA <- my_xts[ , colSums(is.na(my_xts)) != nrow(my_xts)] # Drop all-NA columns xts_all_NA # col1 col3 # 2016-07-12 12 2 # 2022-11-13 13 1 # 2022-11-26 14 NA # 2024-03-11 11 3
Related Tutorials
Below, you may find some further resources on topics such as time objects, descriptive statistics, and data conversion: