Section 42 Combine Data
42.1 Combine columns
If the two or more sets of data have an equal set of rows, and the order of the rows is identical in all datasets, adding columns in these datasets are practical.
The functions to use:
cbind
anddata.frame
set.seed(123)
ID <- paste0('S',1:5)
Sex <- sample(x = c('M','F'), size = length(ID), replace = TRUE)
DF1 <- data.frame(ID=ID, Sex=Sex)
ID <- paste0('S',1:5)
Ht1 <- sample(45:55, size = length(ID), replace = FALSE)
Ht2 <- sample(60:70, size = length(ID), replace = TRUE)
Ht3 <- sample(75:85, size = length(ID), replace = TRUE)
DF2 <- data.frame(ID=ID, Ht1=Ht1, Ht2=Ht2, Ht3=Ht3)
# cbind
DF <- cbind(DF1, DF2[,c('Ht1','Ht2','Ht3')])
DF
rm(DF)
# data.frame
DF <- data.frame(DF1, DF2[,c('Ht1','Ht2','Ht3')])
DF
42.2 Combine rows
If the two or more sets of data have the same columns, and the order of the columns is identical in all datasets, adding row in these datasets are practical.
The functions to use:
rbind
set.seed(123)
ID <- paste0('S',1:5)
Sex <- sample(x = c('M','F'), size = length(ID), replace = TRUE)
Ht1 <- sample(45:55, size = length(ID), replace = FALSE)
Ht2 <- sample(60:70, size = length(ID), replace = TRUE)
Ht3 <- sample(75:85, size = length(ID), replace = TRUE)
DF1 <- data.frame(ID=ID[1:3], Sex=Sex[1:3],
Ht1=Ht1[1:3], Ht2=Ht2[1:3], Ht3=Ht3[1:3])
DF2 <- data.frame(ID=ID[4:5], Sex=Sex[4:5],
Ht1=Ht1[4:5], Ht2=Ht2[4:5], Ht3=Ht3[4:5])
# rbind
DF <- rbind(DF1, DF2)
DF
rm(DF)