生成R中不同数据帧的值之间的排列

时间:2017-09-01 10:44:21

标签: r

我正在寻找能够帮助我生成数据帧值组合的基本R解决方案。我有两个数据框;

[df1]
Col1Name    Col1Reference
first   a
first   b
first   c

[df2]
Col2Name    Col2Reference
second  a
third   b

我想生成一个新的数据框,以便[df2]的新列分配给[df1]的新列,如下所示;

Col1Name    Col1Reference   Col2Name    Col2Reference
first   a   second  a
first   b   second  a
first   c   second  a
first   a   third   b
first   b   third   b
first   c   thid    b

有人能帮忙吗?任何建议都会非常感激。

2 个答案:

答案 0 :(得分:0)

尝试:

cbind(df1[rep(seq_len(nrow(df1)),nrow(df2)),],
      df2[rep(seq_len(nrow(df2)),each=nrow(df1)),])
#    Col1Name Col1Reference Col2Name Col2Reference
#1      first             a   second             a
#2      first             b   second             a
#3      first             c   second             a
#1.1    first             a    third             b
#2.1    first             b    third             b
#3.1    first             c    third             b

答案 1 :(得分:0)

这是一种基于expand.grid的方法:

df1= data.frame(col1="first",col2=letters[1:3],stringsAsFactors = FALSE)
df2= data.frame(col1=c("second","third"),col2=letters[1:2],stringsAsFactors = FALSE)

indices=expand.grid(1:nrow(df1),1:nrow(df2))
cbind(df1[indices[,1],],df2[indices[,2],])

结果(你可能只想调整rownames)

     col1 col2   col1 col2
1   first    a second    a
2   first    b second    a
3   first    c second    a
1.1 first    a  third    b
2.1 first    b  third    b
3.1 first    c  third    b