Add id column then use merge:
df1$id <- seq(nrow(df1))
df2$id <- seq(nrow(df2))
merge(df1, df2, by = "id", all.x = TRUE)
# id LungCap Age Height Smoke Gender Caesarean Gender_1 Age_1
# 1 1 6.475 6 62.1 no male no 1 23
# 2 2 10.125 18 74.7 yes female no 1 35
# 3 3 9.550 16 69.7 no female yes 2 47
# 4 4 11.125 14 71.0 no male no 2 58
# 5 5 4.800 5 56.9 no male no NA NA
# 6 6 6.225 11 58.7 no female no NA NA
# 7 7 4.950 8 63.3 no male yes NA NA
# 8 8 7.325 11 70.4 no male no NA NA
# 9 9 8.875 15 70.5 no male no NA NA
Or Using custom function from StackOverflow post - Column bind with fill:
cbind.fill <- function(...){
nm <- list(...)
nm <- lapply(nm, as.matrix)
n <- max(sapply(nm, nrow))
do.call(cbind, lapply(nm, function (x)
rbind(x, matrix(, n-nrow(x), ncol(x)))))
}
result <- data.frame(cbind.fill(df1, df2))
result
# LungCap Age Height Smoke Gender Caesarean Gender_1 Age_1
# 1 6.475 6 62.1 no male no 1 23
# 2 10.125 18 74.7 yes female no 1 35
# 3 9.550 16 69.7 no female yes 2 47
# 4 11.125 14 71.0 no male no 2 58
# 5 4.800 5 56.9 no male no <NA> <NA>
# 6 6.225 11 58.7 no female no <NA> <NA>
# 7 4.950 8 63.3 no male yes <NA> <NA>
# 8 7.325 11 70.4 no male no <NA> <NA>
# 9 8.875 15 70.5 no male no <NA> <NA>
Example data input:
df1 <- read.table(text = "LungCap Age Height Smoke Gender Caesarean
6.475 6 62.1 no male no
10.125 18 74.7 yes female no
9.55 16 69.7 no female yes
11.125 14 71 no male no
4.8 5 56.9 no male no
6.225 11 58.7 no female no
4.95 8 63.3 no male yes
7.325 11 70.4 no male no
8.875 15 70.5 no male no", header = TRUE)
df2 <- read.table(text = "Gender_1 Age_1
1 23
1 35
2 47
2 58", header = TRUE)
Please provide example input and expected output.
The example input
The table where it should be inserted
I want to add the input column to the side of existing table and number of rows differs between and I don`t want the data to be recycled
Looks like a job for
merge
, what is the expected output for this example data?This is what I want.