0
votes

I have been doing some research on the solution to my problem and I think it lies somewhere in daply. I need to take my data frame split it by boat name add 0.1 to net # every time the activity changes and then combine the data sets. My data frame looks like this.

Boat    Net #    Activity
Ray F    40        Lift 
Dawn     67        Lift 
Ray F    40        Set
Dawn     67        Set
Ray F    40        Lift
Ray F    40        Set
Ray F    40        Lift
Dawn     67        Lift 

After I apply the functions I need the frame to look like this. Essentially adding 0.1 to the net # each time Activity = Set, but the boats are independent of each other.

Boat    Net #    Activity
Ray F    40.0        Lift 
Dawn     67.0        Lift 
Ray F    40.1        Set
Dawn     67.1        Set
Ray F    40.1        Lift
Ray F    40.2        Set
Ray F    40.2        Lift
Dawn     67.1        Lift

I have been using this function to add 0.1 to net # for every change in Activity, and it has worked really well but does not take into consideration the boat name.

df$`Net #` <- df$`Net #` + seq(0, 1, by = 0.1)[with(df, cumsum(c(TRUE, Activity[-1]!= Activity[-length(Activity)])))] + 1

Initially I tried to use Split, and then apply the function but that did nothing so I switched to daply. I tried this and got the following error:

daply(df, df$Boat, .fun = df$`Net #` + seq(0, 1, by = 0.1)[with(df, cumsum(c(TRUE, Activity[-1]!= Activity[-length(Activity)])))] + 1)

Error in parse(text = x) : <text>:1:6: unexpected symbol
1: Dawn Marie
     ^

I think I am on the right path but any help would be great.

1
That's a terrible column name. Why not save yourself the hassle and just make it Net.Rich Scriven

1 Answers

0
votes

Using dplyr package and the %>% operator:

df <- df %>% group_by(Boat) %>% mutate(Net = Net + cumsum(Activity == "Set") * 0.1) %>% ungroup

we have the answer:

   Boat  Net Activity
1 Ray F 40.0     Lift
2  Dawn 67.0     Lift
3 Ray F 40.1      Set
4  Dawn 67.1      Set
5 Ray F 40.1     Lift
6 Ray F 40.2      Set
7 Ray F 40.2     Lift
8  Dawn 67.1     Lift

The same code but without the %>% if you prefer:

df <- ungroup(mutate(group_by(df, Boat), Net = Net + cumsum(Activity == "Set") * 0.1))