Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to duplicate rows in R and add new data?

Tags:

r

I have a data.table of timestamp data that has both time in and time out for people, rounded to the nearest 15 minute intervals. I want to be able to duplicate each row to have the same number of copies as the number of 15 minute intervals their time-in/time-out data covers, while adding a new column that lists the 15 minute interval (e.g. given a person clocking in at 10:00am and clocking out at 11:00am, there would be four rows made, one with time saying 10:00am, one saying 10:15am, one saying 10:30am, and one saying 10:45am).

like image 570
Gabriel Rosen-Duran Avatar asked Dec 02 '25 06:12

Gabriel Rosen-Duran


1 Answers

I have no idea what your data looks like but here is my best shot.

library(padr)
library(zoo)

#data
user<-"4"
times<-c("10:00","11:15")
times<-as.POSIXct(times,format="%H:%M")

#create df
dt<-data.frame(user,times)

> dt
  user               times
1    4 2018-05-31 10:00:00
2    4 2018-05-31 11:15:00

#make correct intervals
dt<-pad(dt, interval="15 min")

#carry user id forward
dt<-na.locf(dt)

>dt

  user               times
1    4 2018-05-31 10:00:00
2    4 2018-05-31 10:15:00
3    4 2018-05-31 10:30:00
4    4 2018-05-31 10:45:00
5    4 2018-05-31 11:00:00
6    4 2018-05-31 11:15:00
like image 162
Chabo Avatar answered Dec 04 '25 00:12

Chabo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!