R:按键变量绑定列

时间:2018-03-07 19:02:10

标签: r left-join inner-join cbind

我想将df1中的两个数据框df2x1组合成一个关键变量的不同组。它基本上是一些连接操作,但是,我不希望行复制并且不关心添加的列之间的关系。

假设:

df1

x1 x2 
A  1
A  2
A  3
B  4
B  5
C  6
C  7

df2

x1 x3 
A  a
A  b
A  c
A  d
A  e
A  f
B  g
C  h

结果应如下所示。

df1 + df2

x1 x2 x3 
A  1  a
A  2  b
A  3  c
A  NA d
A  NA f
B  4  g
B  5  NA
C  6  h
C  7  NA

有没有人有想法?我非常感谢你的帮助!

2 个答案:

答案 0 :(得分:1)

要复制生成的data.frame,您可以按x1创建行ID,然后合并这些行ID和x1(但我不知道这是不是你想要完成)

library(data.table)

df1 = read.table(text = "x1 x2 
A  1
A  2
A  3
B  4
B  5
C  6
C  7", header = T)

df2 = read.table(text = "x1 x3 
A  a
A  b
A  c
A  d
A  e
A  f
B  g
C  h", header = T)

setDT(df1) 
setDT(df2)
df1[, rowid := seq(.N), by = x1] # create rowid
df2[, rowid := seq(.N), by = x1] # create rowid

merge(df1, df2, by = c("x1", "rowid"), all = T)[, rowid := NULL][]

    x1 x2 x3
 1:  A  1  a
 2:  A  2  b
 3:  A  3  c
 4:  A NA  d
 5:  A NA  e
 6:  A NA  f
 7:  B  4  g
 8:  B  5 NA
 9:  C  6  h
10:  C  7 NA

答案 1 :(得分:1)

dplyr中的full_join也适用于此。见下文:

  #recreate your data
  library (data.table)
  library (dplyr)

  df1 <- data.table (x1 = c("A","A","A","B","B","C","C"), x2 = seq (from = 1, to = 7))

  df2 <- data.table (x1 = c("A","A","A","A","A","A","B","C"), x3 = c("a","b","c","d","e","f","g","h" ))

  df1[, rowid := rowid(x1)]

  df2[, rowid := rowid(x1)]

  df3 <- full_join (df1, df2, by = c ("x1","rowid"))

  df3$rowid <- NULL

  setorder (df3, x1)