简体   繁体   English

ifelse函数-替换的长度为零R

[英]ifelse function - replacement has length zero R

I have a dataset BBB which is a list and contains (0,1,2) values and Xx 37232 obs. 我有一个数据集BBB ,它是一个列表,包含(0,1,2)值和Xx 37232 obs。 of 1 variable. 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

Then I made a rule to get values which according to their positions I am going to subset Xx later 然后我制定了一条规则来获取值,这些值将根据它们的位置稍后XxXx子集

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)

So the subset works like following: Xx[B[5,]:S[5,],] 因此,子集的工作方式如下: Xx[B[5,]:S[5,],]

[1] -0.008050324 -0.007825664 -0.008471562 -0.008986408

Now I want to make a new rule to save the first value of each subset of Xx which is higher or equal to 0.004 现在,我想制定一条新规则来保存Xx的每个子集的第一个值,该值大于或等于0.004

For example: 例如:

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

So I wrote the following code: 所以我写了下面的代码:

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

But when applying it I am getting the following error: 但是当应用它时,出现以下错误:

Error in SSS[i] <- ifelse(head(which(Xx[B[i, ]:S[i, ], ] >= : replacement has length zero

You may want to try this structure for your ifelse statement 您可能需要为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))
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM