Question

I have the data from the activity of a website :

DAY | NB_USERS_CONNECTED 
 1  | 10                 
 2  | 14                 
 3  | 15                
 4  | 11                 
 5  | 17              
 6  | 11                

How can I do reshape the data frame in order to create a column with the number of users who was connected the day before? :

DAY | NB_USERS_CONNECTED_DAY0 | NB_USERS_CONNECTED_DAY_-1 
 1  | 10                      | NA     
 2  | 14                      | 10
 3  | 15                      | 14
 4  | 11                      | 15
 5  | 17                      | 11
 6  | 11                      | 17

If possible I'd like to use a method which can also do the job with a lag of 2 days NB_USERS_CONNECTED_DAY_-1 & NB_USERS_CONNECTED_DAY_-2

Was it helpful?

Solution

You can use head with a negative argument:

transform(dat,day_before=c(NA,head(dat$NB_USERS_CONNECTED,-1)))
  DAY NB_USERS_CONNECTED day_before
1   1                 10         NA
2   2                 14         10
3   3                 15         14
4   4                 11         15
5   5                 17         11
6   6                 11         17
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top