Home > Software design >  How to merge a single measurement into a dataframe of multiple measurements in R
How to merge a single measurement into a dataframe of multiple measurements in R

Time:12-14

I have a long dataframe of multiple measurements per ID, at different time points for variables BP1 and BP2.

ID <- c(1,1,1,2,2,2,3,3,4)
Time <- c(56,57,58,61,62,64,66,67,72)
BP1 <- c(70,73,73,74,75,76,74,74,70)
BP2 <- c(122,122,123,126,124,121,130,132,140)
df1 <- data.frame(ID, Time, BP1, BP2)

df1

I would like to merge another dataframe (df2), which contains a single measurement for BP1 and BP2 per ID.

ID <- c(1,2,3,4)
Time <- c(55, 60, 65, 70)
BP1 <- c(70, 72, 73, 74)
BP2 <- c(120, 124, 130, 134)
df2 <- data.frame(ID, Time, BP1, BP2)

df2

How do I combine these dataframes so that the Time variable is in order, and the dataframe looks like this:

df3

Any help greatly appreciated, thank you!

CodePudding user response:

In base R, use rbind() to combine and order() to sort, then clean up the rownames:

df3 <- rbind(df1, df2)
df3 <- df3[order(df3$ID, df3$Time), ]
rownames(df3) <- seq(nrow(df3))

df3

Or, using dplyr:

library(dplyr)

bind_rows(df1, df2) %>%
  arrange(ID, Time)

Result from either approach:

   ID Time BP1 BP2
1   1   55  70 120
2   1   56  70 122
3   1   57  73 122
4   1   58  73 123
5   2   60  72 124
6   2   61  74 126
7   2   62  75 124
8   2   64  76 121
9   3   65  73 130
10  3   66  74 130
11  3   67  74 132
12  4   70  74 134
13  4   72  70 140
  • Related