简体   繁体   English

通过在第二个数据帧的非常列之间插入一个数据帧的列来连接两个数据帧

[英]Join two data frames by inserting columns of one data frame in between very columns of the second data frame

I have a data frame df1 which looks like this 我有一个看起来像这样的数据框df1

A_1 B_1 C_1

a1  e1  i1

b1  f1  l1

c1  g1  m1

d1  h1  n1

I have then another data frame df2 which looks like this 然后,我有另一个数据框df2,看起来像这样

A_2 B_2 C_2

a2  e2  i2

b2  f2  l2

c2  g2  m2

d2  h2  n2

I would like to merge the two df and obtain something like this: 我想将两个df合并并获得如下内容:

A_1  A_2  B_1  B_2  C_1   C_2

a1    a2  e1   e2    i1    i2

b1    b2  f1   f2    l1    l2

c1    c2  g1   g2    m1    m2

d1    d2  h1   h2    n1    n2

A dplyr way: dplyr方式:

library(dplyr)

df %>%
  bind_cols(df2) %>%
  select(sort(current_vars()))

Output: 输出:

   A_1 A_2 B_1 B_2 C_1 C_2
1:  a1  a2  e1  e2  i1  i2
2:  b1  b2  f1  f2  l1  l2
3:  c1  c2  g1  g2  m1  m2
4:  d1  d2  h1  h2  n1  n2

You can cbind them together and then use this answer to select the columns in the order you want (interleave the colnames of the two data frames). 您可以cbind它们cbind在一起,然后使用此答案按所需顺序选择列(交错两个数据框的名称)。

cbind(df1, df2)[c(rbind(names(df1), names(df2)))]

#   A_1 A_2 B_1 B_2 C_1 C_2
# 1  a1  a2  e1  e2  i1  i2
# 2  b1  b2  f1  f2  l1  l2
# 3  c1  c2  g1  g2  m1  m2
# 4  d1  d2  h1  h2  n1  n2

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

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