TeoK
TeoK

Reputation: 501

Calculate value using row with pattern

I have these inputs: df

# A tibble: 53 x 2
   Task              Frame
   <chr>             <int>
 1 S101-10061            6
 2 S101-10061-74716     16
 3 S101-10065           18
 4 S101-10065-104934    16
 5 S101-10071           32
 6 S101-10071-104898    74
 7 S101-10072            8
 8 S101-10072-79124     58
 9 S101-10074           38
10 S101-10075           82

As you see in same "Task" first 10 characters sometimes is same. So I need to find that task is a same, for example task 1 (S101-10061) as same task 2 (S101-10061-74716) in first 10 characters, and if that same find abs difference from number of frame, here in example 16-6=10. So I expect something like:

  Task              Frame  Diff
   <chr>             <int> <int>
 1 S101-10061            6     6
 2 S101-10061-74716     16    
 3 S101-10065           18     2
 4 S101-10065-104934    16     
 5 S101-10071           32    24
 6 S101-10071-104898    74    
 7 S101-10072            8    50
 8 S101-10072-79124     58    
 9 S101-10074           38    
10 S101-10075           82    

I tried:

df %>% mutate(
    Diff = accumulate(
    Frame[1:n()], function(x,y)(abs(x-y))
                        )
    )

But its doesn't help, how to compare row by pattern? any ideas?

Upvotes: 1

Views: 34

Answers (1)

Rui Barradas
Rui Barradas

Reputation: 76402

Here is a dplyr solution.

library(dplyr)

df %>%
  mutate(Task = substr(Task, 1, 10)) %>%
  group_by(Task) %>%
  mutate(Diff = abs(Frame - lead(Frame)))

Data.

df <-
structure(list(Task = c("S101-10061", "S101-10061-74716", "S101-10065", 
"S101-10065-104934", "S101-10071", "S101-10071-104898", "S101-10072", 
"S101-10072-79124", "S101-10074", "S101-10075"), Frame = c(6L, 
16L, 18L, 16L, 32L, 74L, 8L, 58L, 38L, 82L)), class = "data.frame", 
row.names = c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10"))

Upvotes: 1

Related Questions