0

I need someone to help me to delete the rows that has zero values by using R

R codes:

library(glmnet)
library(forecast)
library(Hmisc)
set.seed(54321)
nsim <- 10
n <- 50
phi <- c(0.5,-0.2)
coeffs <- matrix(0L, nrow=nsim, ncol=2)
for (i in 1: nsim) {
    xt <- unclass(arima.sim(n=n,list(ar=phi),innov=rnorm(n,0,1)))
    x.lag1 <- Lag(xt, shift=1)
    x.lag2 <- Lag(xt, shift=2)
    x <- matrix(xt)
    xt_1 <- matrix(x.lag1, ncol=1)
    xt_2 <- matrix(x.lag2, ncol=1)
    data <- cbind(x, 0, xt_1, xt_2)
    cv.lasso2 <- cv.glmnet(data[3:n,2:4],
    data[3:n,1],
    intercept=FALSE,
    alpha=1)
    coeff <- coef(cv.lasso2, s=cv.lasso2$lambda.min)
    coeffs[i,] <- c(coeff[3],coeff[4])
    print(coeffs[i,])
}

Output:

[1]  0.7235772 -0.2384828
[1] 0.4173081 0.0000000
[1]  0.7199519 -0.2195367
[1]  0.6960947 -0.2991648
[1]  0.7680741 -0.3498053
[1] 0.4830431 0.0000000
[1] 0 0
[1] 0.38389815 0.05664054
[1]  0.6764061 -0.1468669
[1] 0.343469 0.000000

I need help with R codes to get the following output, please

 [1]  0.7235772 -0.2384828
 [1]  0.7199519 -0.2195367
 [1]  0.6960947 -0.2991648
 [1]  0.7680741 -0.3498053
 [1]  0.38389815 0.05664054
 [1]  0.6764061 -0.1468669

Thank you in advance

daedsidog
  • 1,732
  • 2
  • 17
  • 36
ALRADDADI
  • 37
  • 6

2 Answers2

0

coeffs == 0 should produce a boolean matrix of where cells are equal to zero. rowSums that then equal 0 are those you want to keep, so another check is done which is used to subset the original matrix coeffs.

coeffs[rowSums(coeffs == 0) == 0, ]
zacdav
  • 4,603
  • 2
  • 16
  • 37
-1
subset(coeffs, apply(coeffs, 1, function(x) all(x != 0)))
Brian Syzdek
  • 873
  • 6
  • 10