首页 文章

R代码删除任何零值的行[重复]

提问于
浏览
-1

这个问题在这里已有答案:

我需要有人通过使用R来帮助我删除具有零值的行

R代码:

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,])
}

输出:

[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

我需要R代码的帮助才能获得以下输出

[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

先感谢您

2 回答

  • 0
    subset(coeffs, apply(coeffs, 1, function(x) all(x != 0)))
    
  • -1

    coeffs == 0 应该产生一个布尔矩阵,其中单元格等于零 . rowSums 然后等于0是你想要保留的那个,所以进行另一次检查,用于子集原始矩阵 coeffs .

    coeffs[rowSums(coeffs == 0) == 0, ]
    

相关问题