user3355655
user3355655

Reputation: 485

R - Index position with condition

I've 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 would like an 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 to a data frame.

Thanks

edit : w is a data frame,

roughly 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 with a return to 1 when value 1 is 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

Upvotes: 3

Views: 3269

Answers (2)

ARobertson
ARobertson

Reputation: 2897

For the given data including repeated 1's 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 does not start on 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)

Upvotes: 1

akrun
akrun

Reputation: 887118

This assumes that the data is ordered in the way shown in 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

Upvotes: 2

Related Questions