我有一个数据集BBB
,它是一个列表,包含(0,1,2)
值和Xx
37232 obs。 1变量。
head(Xx)
Xx
1 NA
2 0.0006458981
3 0.0014977347
4 0.0021436328
5 0.0018066425
head(BBB)
$`1`
[1] 1 2 0 0 0 0
$`2`
[1] 1 2 0
然后我制定了一个规则来获取根据他们的位置我将稍后将Xx
分组的值
B<-rep(NA,(length(BBB)-2))
for(i in 1:(length(BBB)-2)){B[i]<-length(BBB[[i]])+as.numeric(which(BBB[[i+1]]==1))}
S<-rep(NA,(length(BBB)-2))
for(i in 1:(length(BBB)-2)){S[i]<-length(BBB[[i]])+as.numeric(which(BBB[[i+1]]==2))}
B<-as.data.frame(B)
S<-as.data.frame(S)
因此子集的工作原理如下:
Xx[B[5,]:S[5,],]
[1] -0.008050324 -0.007825664 -0.008471562 -0.008986408
现在我想制定一条新规则来保存Xx
的每个子集的第一个值,该值高于或等于0.004
例如:
which(Xx[B[13,]:S[13,],]>=.0001)
[1] 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
head(which(Xx[B[13,]:S[13,],]>=.0001),n=1)
[1] 277
所以我写了下面的代码:
SSS<-rep(NA,length(Xx))
for(i in 2:length(Xx)){SSS[i]<-ifelse(head(which(Xx[B[i,]:S[i,],]>=.004),n=1),
Xx[head(which(Xx[B[i,]:S[i,],]>=.004),n=1),],
tail(Xx[B[i,]:S[i,],]),n=1))}
但是在应用它时我收到以下错误:
Error in SSS[i] <- ifelse(head(which(Xx[B[i, ]:S[i, ], ] >= :
replacement has length zero
答案 0 :(得分:0)
您可能想要为ifelse语句尝试此结构
SSS<-rep(NA,length(Xx))
for(i in 2:length(Xx)){
SSS[i] <- ifelse(length(which(Xx[B[i,]:S[i,],] >= .004)) > 0,
# If there are any values GTE .004, then return the first result GTE .004
Xx[head(which(Xx[B[i,]:S[i,],] >= .004), n=1),],
# If there are no values GTE .004, then return the last value of subset
tail(Xx[B[i,]:S[i,],]),n=1))
}