Date <- Reduce(intersect, list(df$Date1, df$Date2, df$Date3, df$Date4)) Value1 <- df[df$Date1 %in% Date, ]$Value1 Value2 <- df[df$Date2 %in% Date, ]$Value2 Value3 <- df[df$Date3 %in% Date, ]$Value3 Value4 <- df[df$Date4 %in% Date, ]$Value4 data.frame(Date, Value1, Value2, Value3, Value4)
As mentioned in @docendo discimus, this can be long in case of multiple columns, the updated way would be
Date <- Reduce(intersect, list(df$Date1, df$Date2, df$Date3, df$Date4)) Values <- df[, seq(0, ncol(df), by=2)] Dates <- df[, seq(1, ncol(df), by=2)] mat <- apply(Dates, 2, function(x) {x %in% Date}) data.frame(Date, matrix(Values[mat], nrow = 4))
According to @David's comments, this can be improved using
Values <- df[c(FALSE, TRUE)] Dates <- df[c(TRUE, FALSE)] Date <- Reduce(intersect, as.list(Dates)) mat <- apply(Dates, 2, function(x) {x %in% Date}) data.frame(Date, matrix(Values[mat], nrow = ncol(df)/2))