2017-02-14 74 views
0

如何創建一個表具有以下數據:表具有多個因變量

初始數據表:

enter image description here

完表結果:

enter image description here

這裏將是容易輸入到R的代碼(我將在操作期間從csv文件中讀取):

Date = c(20170101,20170101,20170102,20170102,20170102,20170102,20170103) 
Person = c("Adam","Adam","Adam","Ben","Ben","Ben","Ben") 
Fruit = c("Apple", "Pear","Bananna","Blueberry","Cherry","Grape","Grape") 
z= data.frame(Date,Person,Fruit) 
+1

一般而言,您應同時顯示輸出並描述來自inp的轉換規則ut輸出是。我正在刪除data.table標記,因爲您只應該使用它來了解有關該包的問題,​​而不僅僅是要關注跟隨標記或請求該包的答案的人的注意力,甚至不需要自己安裝它... – Frank

+0

The邏輯似乎沒問題,但我們應該警告:1)在數據框中創建空格,2)將多個項目堆疊到一個矢量位置。這是可能的,但你會對穀物工作 –

+0

現在試試這個'reshape2 :: dcast(z,Person〜Date,value.var =「Fruit」,fun = toString)' –

回答

1

tapply()功能可以使用c函數值安排成一個矩陣對象。值獲得封裝在名單:

with(z, tapply(Fruit, list(Person,Date), FUN=c)) 

    20170101 20170102 20170103 
Adam Character,2 "Bananna" NULL  
Ben NULL  Character,3 "Grape" 

然後,您可以顯示矩陣對象與奉迎:

library(pander) 
panderOptions('keep.line.breaks', TRUE) 
mytable <- with(z, tapply(Fruit, list(Person,Date), FUN=c)) 
pandoc.table(mytable, style="multiline") 

---------------------------------------------------------- 
    &nbsp; 20170101   20170102   20170103 
---------- ----------- ------------------------ ---------- 
**Adam** Apple, Pear   Bananna    NULL 

**Ben**  NULL  Blueberry, Cherry, Grape Grape 
---------------------------------------------------------- 

如果你想分離的「細胞」行,你可以使用樣式=「網格」。然後,輸出看起來像:

+----------+-------------+--------------------------+------------+ 
| Person | 20170101 |   20170102   | 20170103 | 
+==========+=============+==========================+============+ 
| Adam | Apple, Pear |   Bananna   |   | 
+----------+-------------+--------------------------+------------+ 
| Ben |    | Blueberry, Cherry, Grape | Grape | 
+----------+-------------+--------------------------+------------+ 

如果使用paste0與崩潰,你可以刪除逗號並使用換行來代替:

mytable <- with(z, tapply(Fruit, list(Person,Date), FUN=paste0, collapse="\n")) 

矩陣的結構是現在不同了,每個條目是一個長度爲1的字符值,但隨後會顯示在一個pandoc表中,每個Fruit顯示在一行上:

pandoc.table(mytable, style="multiline") # or style ="grid" as above 
#------------ 
------------------------------------------- 
    &nbsp; 20170101 20170102 20170103 
---------- ---------- ---------- ---------- 
**Adam** Apple  Bananna  NA  
       Pear       

**Ben**  NA  Blueberry Grape 
         Cherry    
         Grape    
-------------------------------------------