I am looking to apply a function to a data frame and then store the results of that function in a new column in the data frame.
Here is a sample of my data frame, tradeData:
Login AL Diff
a 1 0
a 1 0
a 1 0
a 0 1
a 0 0
a 0 0
a 0 0
a 1 -1
a 1 0
a 0 1
a 1 -1
a 1 0
a 0 1
b 1 0
b 0 1
b 0 0
b 0 0
b 1 -1
c 1 0
c 1 0
c 0 1
c 0 0
c 1 -1
Where the "Diff" column is the column I am trying to add. It just just the difference between the values row(x-1) and row(x) of tradeData, grouped by Login.
Here are some samples of what I've tried:
tradeData$Diff = ave(tradeData$AL,tradeData$Login,FUN = function(x) {diff(x)})
and
tradeData$Diff = as.data.frame(with(tradeData,tapply(AL,Login,FUN = diff)))
I've found the following question useful thus far: R applying a function to a subset of a data frame but I am unsure how to proceed from here, as I keep getting errors.
Thanks