I am trying to merge multiple data frames. Let's assume I have the following data frames:
library(tidyverse)
id <- c(10, 10, 12, 12, 13)
data <- c(500, 600, 700, 800, 900)
data1 <- data.frame(id, data)
id <- c(10, 12, 13, 14)
data <- c(550, 850, 950, 1050)
data2 <- data.frame(id, data)
id <- c(15)
data <- c(1350)
data3 <- data.frame(id, data)
Now I want to join the data frames so that the output looks like this:
> srtdata
id data
1 10 500
2 10 600
6 10 550
3 12 700
4 12 800
7 12 850
5 13 900
8 13 950
9 14 1050
10 15 1350
This is the way I did this.
mdata1 <- dplyr::full_join(data1, data2)
mdata2 <- dplyr::full_join(mdata1, data3)
I have to write two lines as it seems full_join
can take two frames x
and y
at a time.
To order the data in a correct way I am using order from base R:
srtdata <- mdata2[order(mdata2$id), ]
Anyone here to help me finding a better solution?