jeudi 28 juin 2018

r ifelse condition for the calculation on multiple dataframes

I have 3 data frames, df 1 = a time interval, df2 = list of IDs, df3 = list of IDs with associated date.

df1 <- structure(list(season = structure(c(2L, 1L), .Label = c("summer", 
"winter"), class = "factor"), mindate = structure(c(1420088400, 
1433131200), class = c("POSIXct", "POSIXt")), maxdate = structure(c(1433131140, 
1448945940), class = c("POSIXct", "POSIXt")), diff = structure(c(150.957638888889, 
183.040972222222), units = "days", class = "difftime")), .Names = c("season", 
"mindate", "maxdate", "diff"), row.names = c(NA, -2L), class = "data.frame")

df2 <- structure(list(ID = c(12345, 12345, 12345)), .Names = "ID", row.names = c(NA, 
-3L), class = "data.frame")

df3 <- structure(list(ID = c(12345, 123456), time = structure(c(1420866000, 
1451624400), class = c("POSIXct", "POSIXt"))), .Names = c("ID", 
"time"), row.names = c(NA, -2L), class = "data.frame")

What i would like to achieve, is if the ID in df2 finds a match in df3, and if the time in df3 is equal or larger than the mindate & equal or smaller than the maxdate in df1, then calculate the time difference between maxdate (df1) and time (df3) of the associated ID. I tried using the ifelse function. It works when I manually specify the match in IDs between df2 and df3, but i need the function to find the match in IDs, and then execute the time difference calculation.

df1$result <- ifelse(df2[1,1] == df3[1,1] & df3[1,2] >= df1$mindate & df3[1,2] <= df1$maxdate, 
                     difftime(df1$maxdate,df3[1,2],units="days"),
                     difftime(df1$maxdate,df1$mindate,units="days")

Thanks for any help

Aucun commentaire:

Enregistrer un commentaire