简体   繁体   English

在 R 中连接 2 列不同的行数

[英]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.我正在尝试创建一个 dataframe,其中包含两列,行数不同,但我不知道该怎么做。 Basically I would complete the lower columns with NA.基本上我会用 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有一个cbind.na ,它用NA填充较短的长度 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 Output是一个matrix ,可以用as.data.frame转成data.frame


Or using base R或者使用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 :另一种可能的解决方案,使用 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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