简体   繁体   中英

Getting a difference between time(n+1)-time(n) in a dataframe in r

I have a dataframe where the columns represent monthly data and the rows different simulations. the data I am working with accumulates over time so I want to take the difference between the months to get the true value for that month. There are not headers for my data frame

For example:

View(df)=

1  3  4  6  19  23  24  25  26 ...
1  2  3  4  5   6   7   8   9  ...
0  0  2  3  5   7   14  14  14 ...

My plan was to use the diff() function or something like it, but I am having trouble using it on a dataframe.

I have tried:

df1<-diff(df, lag = 1, differences = 1)

but only get zeros.

I am grateful for any advice.

see ?apply . If it's a data frame

apply(df,2,diff)

should work. Also since a dataframe is a list of vectors sapply(df,diff) should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM