R - index position with the condition

I have a data frame like this

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 want the index position starting after the 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 to a data frame.

thank

edit: w is the dataframe,

about this 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 falling back to 1 when 1 matches.

> 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

      

thank

+3


source to share


2 answers


For data including re-1 and non-sequential input, the following 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 the data doesn't start at 1:



m[1,1] <- 2

      

Then this 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)

      

+1


source


This assumes that the data is ordered as shown in the example.



m$wanted <- with(m, ave(w, cumsum(c(TRUE,diff(w) <0)), FUN=seq_along))
m$wanted
 #[1] 1 2 3 4 5 1 2 3 4 5 6 7 1 2 3 4 5 1 2 3 4 5 6 7 8 9

      

+2


source







All Articles