R 使用长度和整数(0)测试条件表达式

R 使用长度和整数(0)测试条件表达式,r,R,我张贴这个问题,这是指一个统计问题,但我的问题是与代码 我有以下95%置信区间内有效值的向量和自相关计算。(t+1处只有一个有效值)包Quantmod x<-c(1,1,3,8,5,2,4,3,1,1,0,5,1,1,3,4,6,7,8,9,4,2,1) a<-acf(x) b<-a[[1]] c<-(b[2:length(b)]) posssignificance_level<-qnorm((1+0.95)/2)/sqrt(sum(!is.na(x))) poss

我张贴这个问题,这是指一个统计问题,但我的问题是与代码

我有以下95%置信区间内有效值的向量和自相关计算。(t+1处只有一个有效值)包Quantmod

x<-c(1,1,3,8,5,2,4,3,1,1,0,5,1,1,3,4,6,7,8,9,4,2,1)
a<-acf(x)
b<-a[[1]]
c<-(b[2:length(b)])
posssignificance_level<-qnorm((1+0.95)/2)/sqrt(sum(!is.na(x)))
posssignificance_level
negsignificance_level<- -posssignificance_level
negsignificance_level
poscorr<-which(posssignificance_level<c)
negcorr<-which(negsignificance_level>c)
poscorr
negcorr

x第一部分解释了为什么
which(…)
表达式返回
整数(0)

我相信这就是你问题的答案:

if length(object) == then expression1 else expression2

posautorrelation <- if(length(poscorr) == 0) Lag(x,0) else Lag(x, poscorr)
posautorrelation
# [1] NA  1  1  3  8  5  2  4  3  1  1  0  5  1  1  3  4  6  7  8  9  4  2

negautorrelation <- if(length(negcorr) == 0) Lag(x,0) else Lag(x, negcorr)
# [1] 1 1 3 8 5 2 4 3 1 1 0 5 1 1 3 4 6 7 8 9 4 2 1
如果长度(对象)=则表达式1其他表达式2
posautorelation
length
可能(在某些问题上)返回一个double。因此,最好使用
if(isTRUE(all.equal(length(poscorr),0))
来解释在长向量上使用时的情况。
posautorrelation <- if((poscorr==integer(0)) Lag(x,0) else Lag(x,poscorr)
Error: inesperado símbolo in "posautorrelation <- if(length(poscorr==integer(0)) Lag"
Error durante el wrapup: no se puede abrir la conexión

negautorrelation <- if((negcorr==integer(0)) Lag(x,0) else Lag(x,negcorr)
Error: inesperado símbolo in "negautorrelation <- if(length(negcorr==integer(0)) Lag"
Error durante el wrapup: no se puede abrir la conexión
print(negsignificance_level)
# [1] -0.4086807

min(c)
# [1] -0.3432622

which(negsignificance_level > c)
# integer(0)
if length(object) == then expression1 else expression2

posautorrelation <- if(length(poscorr) == 0) Lag(x,0) else Lag(x, poscorr)
posautorrelation
# [1] NA  1  1  3  8  5  2  4  3  1  1  0  5  1  1  3  4  6  7  8  9  4  2

negautorrelation <- if(length(negcorr) == 0) Lag(x,0) else Lag(x, negcorr)
# [1] 1 1 3 8 5 2 4 3 1 1 0 5 1 1 3 4 6 7 8 9 4 2 1