2015-08-09 19 views
1

的數據框下面是我的data.frame df樣子:如何使用expand.grid上的字符

df 
color shape type 
red  oval model 1 
blue square model 4 

我需要的是採取使用expand.grid不同行的組合。這裏是我的嘗試:

row1 <- df[1,] 
row2 <- df[2,] 
output <- expand.grid(row1, row2) 

但是,我得到一個錯誤的row1是不是列表載體。

 position1 position2 position3  position4  position5 
1   razor windranger dark seer spirit breaker bounty hunter 
2 blood seeker ember spirit  lina   techie spirit breaker 
3   luna storm spirit dark seer   rubick winter wayvern 
4 phantom lancer storm spirit dark seer   lina  silencer 
5 phantom lancer   lina dark seer   tuskar winter wayvern 
6  gryocopter shadow fiend  tuskar   visage  earthshaker 

我原來data.frame的str(df)

我原來的數據幀的head(df)

'data.frame': 42 obs. of 5 variables: 
$ position1: Factor w/ 15 levels "antimage","blood seeker",..: 13 2 9 12 12 5 9 13 12 4 ... 
$ position2: Factor w/ 12 levels "dragon knight",..: 11 2 9 9 4 7 7 6 4 10 ... 
$ position3: Factor w/ 14 levels "bristle","brood mother",..: 4 6 4 4 4 12 12 3 12 13 ... 
$ position4: Factor w/ 20 levels "bounty hunter",..: 15 16 11 7 17 18 11 12 1 17 ... 
$ position5: Factor w/ 13 levels "ancient apparition",..: 2 10 12 9 12 6 6 4 13 11 ...` 
+2

我認爲這會有所幫助,如果你能指出預期的產出。 – RHertel

回答

1

這將是更好地爲你的代碼...嘗試

row1 <- unlist(df[1,]) 

否則df[1,]是一行數據幀。


我會在@firelittle回覆後編輯此帖子。這裏是一個例子:

> dd <- data.frame(x=factor(LETTERS[1:2]), y=factor(LETTERS[3:4])) 
> dd 
    x y 
1 A C 
2 B D 
> expand.grid(unlist(dd[1,]), unlist(dd[2,])) 
    Var1 Var2 
1 A B 
2 C B 
3 A D 
4 C D 

它是你的預期產出?

+0

數據框只是一個例子。我的原始數據框是5列和100行。當我遵循你的步驟時,結果給出了我在數據框中的其他級別的組合。我也是新來的R,我不知道如何提供所需的代碼 – firelitte

+0

@firelitte請編輯您的帖子並提供'head(df)'和'str(df)'的輸出。 –

+0

請檢查編輯。 thnx – firelitte

相關問題