ashwin baldawa
ashwin baldawa

Reputation: 13

Using Difftime function on Multiple columns of two DataFrames in R

I have two data frames each containing timestamp columns as in the below images:

Dataframe-1:

Dataframe-1

Dataframe-2:

Dataframe-2

I want to find the time difference between each of the respective columns of the data frames, example: Time difference between respective rows of Column1 of DF1 and respective rows of Column1 of DF2.

I have only mentioned three columns in each of the data frame in the above image, although i have 257 columns in each of the column in my original dataset, i am currently finding the difference using the below command individually:

diff_time_1<- difftime(df1$t1,df2$l1)
diff_time_2<- difftime(df1$t2,df2$l2)..so on

This well take a lot of effort if i try to perform for all the 257 columns, i have tried various ways by using the apply functions and for loops, but they do not seem to work.

Kindly help me in finding a solution where i can apply the difftime function to the entire columns in a single go.

Upvotes: 1

Views: 2168

Answers (2)

d.b
d.b

Reputation: 32548

#DATA
mydates = seq.POSIXt(from = as.POSIXct("1970-01-01"),
                     to = as.POSIXct("1970-12-01"), by = "hours")
set.seed(42)
df1 = data.frame(C1 = sample(mydates, 5), C2 = sample(mydates, 5))
df2 = data.frame(C1 = sample(mydates, 5), C2 = sample(mydates, 5))

If the dimension of df1 and df2 are same, you could just subtract to get the difference in days

df1 - df2
#               C1              C2
#1  152.70833 days -140.62500 days
#2   72.79167 days  -80.70833 days
#3 -216.58333 days    5.75000 days
#4  192.00000 days   60.79167 days
#5   59.91667 days   48.33333 days

Or you could use sapply to go through columns of df1 and df2 to use them in difftime

sapply(1:2, function(i) difftime(time1 = df1[,i], time2 = df2[,i], units = "hours"))
#      [,1]  [,2]
#[1,]  3665 -3375
#[2,]  1747 -1937
#[3,] -5198   138
#[4,]  4608  1459
#[5,]  1438  1160

Upvotes: 0

akrun
akrun

Reputation: 887213

We can use Map to apply difftime on corresponding columns of 'df1', 'df2' to get the a list of vectors

Map(difftime, df1, df2)

If the datetime columns are only a subset of the columns, then subset the datasets and apply difftime

Map(difftime, df1[subCols], df2[subCols])

Upvotes: 1

Related Questions