简体   繁体   中英

Join 2 columns of different number of rows in R

I am trying to create a dataframe with two columns with different number of rows, but I have no idea how to do it. Basically I would complete the lower columns with NA. Follow the code:

data.frame(Week1_data, Week2_data)

The error is:

  arguments imply differing number of rows: 802, 1103```

There is a cbind.na which does pad with NA for the shorter length object

qpcR:::cbind.na(Week1_data, Week2_data)
      Week1_data Week2_data
[1,]          1          1
[2,]          2          2
[3,]          3          3
[4,]          4          4
[5,]          5          5
[6,]         NA          6
[7,]         NA          7

Output is a matrix , it can be converted to data.frame with as.data.frame


Or using base R

mx <- max(length(Week1_data), length(Week2_data))
data.frame(lapply(list(Week1_data = Week1_data, 
      Week2_data = Week2_data), `length<-`, mx))
  Week1_data Week2_data
1          1          1
2          2          2
3          3          3
4          4          4
5          5          5
6         NA          6
7         NA          7

data

Week1_data <- 1:5
Week2_data <- 1:7

Another possible solution, using base R merge :

Week1_data <- 8:10
Week2_data <- 2:5

merge(cbind(Week1_data, X=1:length(Week1_data)),
      cbind(Week2_data, X=1:length(Week2_data)), all.y =T)[-1]

#>   Week1_data Week2_data
#> 1          8          2
#> 2          9          3
#> 3         10          4
#> 4         NA          5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM