I have a table stored in a dataframe in R.
I want to calculate the first derivative along each column. Columns are measured variables, rows are time.
Can I vectorize this function ?
df$C <- df$A + df$B
In principle I’d like something like :
df$DiffA <- diff(df$A)
The problem is, that I don’t know how to vectorize functions that need A(n) and A(n+1), where n is the row within the dataframe (Pseudocode).
Based on the comments:
diffreturns one value less then there are values in the input vector (for obvious reasons). You can fix that by prepending or appending anNAvalue.Some timings:
diffis fast, but for big datasets using adata.frameis not efficient. Usedata.tableinstead. The speed gain gets more pronounced, the bigger the dataset is.