Reputation: 795
This is probably very straight forward, but I can't figure out a way to do this. I have some data that looks like this:
domain difference
xxxx 0
xxxx 2
xxxx 14
xxxx 3
xxxx 7
xxxx 2
yyyy 6
yyyy 5
yyyy 13
yyyy 10
zzzz 2
zzzz 5
zzzz 1
zzzz 15
zzzz 16
zzzz 8
zzzz 9
I want it to look like this:
domain difference grp
xxxx 0 1
xxxx 2 1
xxxx 14 2
xxxx 3 2
xxxx 7 2
xxxx 2 2
yyyy 6 1
yyyy 5 1
yyyy 13 1
yyyy 10 1
zzzz 2 1
zzzz 5 1
zzzz 1 1
zzzz 15 2
zzzz 16 3
zzzz 8 3
zzzz 9 3
So basically by domain I want to assign a group number to several rows if the difference is greater than or equal to 14. When there is a difference greater than or equal to 14, assign a group number to the previous rows.
I've tried using a nested for loop, where the domains are levels but I feel like that may be unnecessarily complex, and I'm not sure how to tell the loop to keep going and pick up where it left off after assigning the first group number. Here's what I have so far:
lev <- levels(e_won$domain)
lev <- levels(e_won$domain)
for (i in 1:length(lev)) {
for (j in 1:nrow(lev)){
if (difference[j] >= 14) {
grp[1:j] = 1
}
I'm completely open to a non-loop solution, but that's just what I thought at first.
Upvotes: 1
Views: 1918
Reputation: 887951
You can try
library(data.table)
setDT(df1)[, grp:=cumsum(difference>=14)+1L, by=domain][]
# domain difference grp
#1: xxxx 0 1
#2: xxxx 2 1
#3: xxxx 14 2
#4: xxxx 3 2
#5: xxxx 7 2
#6: xxxx 2 2
#7: yyyy 6 1
#8: yyyy 5 1
#9: yyyy 13 1
#10: yyyy 10 1
#11: zzzz 2 1
#12: zzzz 5 1
#13: zzzz 1 1
#14: zzzz 15 2
#15: zzzz 16 3
#16: zzzz 8 3
#17: zzzz 9 3
Or using dplyr
df1 %>%
group_by(domain) %>%
mutate(grp= cumsum(difference >=14)+1L)
Or using base R
(from @Colonel Beauvel's comments)
df1$grp <- with(df1, ave(difference>=14, domain, FUN=cumsum)) + 1L
Upvotes: 4