【问题标题】:R codes to remove any rows that has zero values [duplicate]R代码删除任何具有零值的行[重复]
【发布时间】:2018-12-09 05:20:50
【问题描述】:

我需要有人帮助我使用 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

提前谢谢你

【问题讨论】:

    标签: r


    【解决方案1】:

    coeffs == 0 应该生成一个布尔矩阵,其中单元格等于零。 rowSums 然后等于 0 是您要保留的那些,因此进行了另一次检查,用于对原始矩阵 coeffs 进行子集化。

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

    【讨论】:

      【解决方案2】:
      subset(coeffs, apply(coeffs, 1, function(x) all(x != 0)))
      

      【讨论】:

        猜你喜欢
        • 2016-06-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-16
        • 1970-01-01
        • 2021-10-21
        • 2017-08-17
        • 1970-01-01
        • 2017-01-17
        相关资源
        最近更新 更多