2017-09-01 53 views
1

不同数据帧的值之间的排列我正在寻找一个基础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 

有人能帮忙吗?任何意见将不胜感激。

回答

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 
+0

出色的作品,谢谢! –

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