loops - R - Remove columns with 0 values in df with 1 or more remaining columns -


i writing piece of r code looping through dataframe , running time series predictions subsetted dataframe. however, manner in created loop gives me number of columns 0 values. there single column non 0 values or many columns non 0 values, there minimum of 1 column non 0 values. each iteration through loop yield different number of non-zero columns.

please see following discussions regarding topic.

remove columns 0 values dataframe

delete columns 0 matrix

how following code work? provide 2 examples captures crux of issue. first example works great , need adapt work.

dat <- data.frame(x = rep(0, 10), y = rnorm(10), z = rep(0, 10), = rnorm(10))  dat <- dat[, colsums(dat) > 0] 

the second example fails because there single column of non 0 values.

dat2 <- data.frame(x = rep(0, 10), y = rep(0, 10), z = rep(0, 10), = rnorm(10)) dat2 <- dat2[, colsums(dat2) > 0] 

any insights appreciated. help.

try either drop=false default drop=true or remove , , return data.frame. more info, please check ?"["

dat2[colsums(dat2) > 0] 

or

dat2[,colsums(dat2) > 0, drop=false] 

if use subset, default drop=false

subset(dat2, select=colsums(dat2) > 0) 

Comments

Popular posts from this blog

facebook - android ACTION_SEND to share with specific application only -

python - Creating a new virtualenv gives a permissions error -

javascript - cocos2d-js draw circle not instantly -