我需要有人帮助我通过使用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
提前谢谢
答案 0 :(得分:0)
coeffs == 0
应该产生一个布尔矩阵,其中单元等于零。
rowSums
等于0就是您要保留的值,因此需要执行另一项检查,该检查用于子集原始矩阵coeffs
。
coeffs[rowSums(coeffs == 0) == 0, ]
答案 1 :(得分:-1)
subset(coeffs, apply(coeffs, 1, function(x) all(x != 0)))