如何使用以下数据创建表格:
初始数据表:
结束表结果:
这里的代码很容易输入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)
答案 0 :(得分: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"
然后,您可以使用pander显示该矩阵对象:
library(pander)
panderOptions('keep.line.breaks', TRUE)
mytable <- with(z, tapply(Fruit, list(Person,Date), FUN=c))
pandoc.table(mytable, style="multiline")
----------------------------------------------------------
20170101 20170102 20170103
---------- ----------- ------------------------ ----------
**Adam** Apple, Pear Bananna NULL
**Ben** NULL Blueberry, Cherry, Grape Grape
----------------------------------------------------------
如果你想要分隔“单元格”的线条,你可以使用style =“grid”。然后输出如下:
+----------+-------------+--------------------------+------------+
| 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
#------------
-------------------------------------------
20170101 20170102 20170103
---------- ---------- ---------- ----------
**Adam** Apple Bananna NA
Pear
**Ben** NA Blueberry Grape
Cherry
Grape
-------------------------------------------