indexing - R - Index position with condition -
indexing - R - Index position with condition -
i've info frame
w<-c(0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0)
i index position starting after value 1.
output : na,na,na,na,na,1,2,3,4,5,6,7,1,2,3,4,5,1,2,3,4,5,6,7,8,9
ideally applicable info frame.
thanks
edit : w info frame,
roughly function
m<-as.data.frame(w) m[m!=1] <- row(m)[m!=1] m w 1 1 2 2 3 3 4 4 5 5 6 1 7 7 8 8 9 9 10 10 11 11 12 12 13 1 14 14 15 15 16 16 17 17 18 1 19 19 20 20 21 21 22 22 23 23 24 24 25 25 26 26
but homecoming 1 when value 1 matching.
> m w wanted 1 1 na 2 2 na 3 3 na 4 4 na 5 5 na 6 1 1 7 7 2 8 8 3 9 9 4 10 10 5 11 11 6 12 12 7 13 1 1 14 14 2 15 15 3 16 16 4 17 17 5 18 1 1 19 19 2 20 20 3 21 21 4 22 22 5 23 23 6 24 24 7 25 25 8 26 26 9
thanks
for given info including repeated 1's , non-sequential input, next works:
m[9,1] <- 100 m[3,1] <- 55 m[14,1] <- 60 m[14,1] <- 60 m[25,1] <- 1 m[19,1] <- 1 m$result <- 1:nrow(m) - which(m$w == 1)[cumsum(m$w == 1)] + 1
but if info not start on 1:
m[1,1] <- 2
then works:
firstone <- which(m$w == 1)[1] subindex <- m[firstone:nrow(m),'w'] == 1 m$result <- c(rep(na,firstone-1),1:length(subindex) - which(subindex)[cumsum(subindex)] + 1)
r indexing condition
Comments
Post a Comment