I am writing a piece of R code which is looping through a dataframe and then running time series predictions from the subsetted dataframe. However, the manner in which I created the loop gives me a number of columns with 0 values. There could a single column with non zero values or many columns with non zero values, but there will always be a minimum of one column with non zero values. Each iteration through the loop could yield a different number of non-zero columns.
Please see the following discussions regarding this topic.
Remove columns with zero values from a dataframe
Delete all columns with 0 from matrix
How do I get the following code to work? I will provide 2 examples that captures the crux of my issue. The first example works great and is exactly what I need to adapt to work.
dat <- data.frame(x = rep(0, 10), y = rnorm(10), z = rep(0, 10), a = rnorm(10))
dat <- dat[, colSums(dat) > 0]
The second example fails because there is only a single column of non zero values.
dat2 <- data.frame(x = rep(0, 10), y = rep(0, 10), z = rep(0, 10), a = rnorm(10))
dat2 <- dat2[, colSums(dat2) > 0]
Any insights would be greatly appreciated. Thanks for the help.