I have 3 data frames that I am trying to merge/join. I've tried these two solutions: Merge multiple data.frames in R with varying row length, Merge data.frames with duplicates. However, the output datatables aren't what I'm looking for.
Here is a sample code of my dataframes:
df1 <- data.frame(FzL = c(594.4014, 594.4147, 594.4148, 594.4194, 594.3877, 618.8600), task = c("hop", "hop", "hop", "vj", "vj", "vj"),
limb = c("L", "L", "L", "R", "R", "R"), trial = c("trial1", "trial1", "trial1", "trial2", "trial2", "trial2"))
df2 <- data.frame(FzR = c(594.2836, 619.1613, 618.8364, 594.4196, 694.3853, 640.2640), task = c("hop", "hop", "hop", "vj", "vj", "vj"),
limb = c("L", "L", "L", "R", "R", "R"), trial = c("trial1", "trial1", "trial1", "trial2", "trial2", "trial2"))
df3 <- data.frame(Frame = c(219388, 219389, 219390, 211387, 211388, 211389), Time = c("2020-06-05 13:26:39", "2020-06-05 13:26:39", "2020-06-05 13:26:39",
"2020-06-05 13:26:39", "2020-06-05 13:26:39", "2020-06-05 13:26:39"),
task = c("hop", "hop", "hop", "vj", "vj", "vj"), limb = c("L", "L", "L", "R", "R", "R"), trial = c("trial1", "trial1", "trial1", "trial2", "trial2", "trial2"))
When trying to merge with this code:
JOIN <- merge(df3, merge(df1, df2, by = c("task", "limb", "trial"), all = TRUE), by = c("task", "limb", "trial"), all = TRUE)
I get a table that duplicates the rows multiple times.
I've also tried this code:
run.seq <- function(x) as.numeric(ave(paste(x), x, FUN = seq_along))
L <- list(df1, df2, df3)
L2 <- lapply(L, function(x) cbind(x, run.seq = run.seq(x$limb)))
out <- Reduce(function(...) merge(..., all = TRUE), L2)
However, it only gives me the first 3 rows and doesn't run through the whole dataset.
My final data table should have 7 columns: task, limb, trial, FzL, FzR, Frame, Time.
Any help would be much appreciated! Thank you.