2017-09-01 83 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