![](/img/trans.png)
[英]In R, how to use “aggregate” or “by” when not all combinations of factors are present?
[英]How do I neatly present the output of different combinations of two factors in a table in r?
我有一个包含3列的数据集。 前两列具有来自实验的以下输入值,它们是因素:
col1=[5, 5, 7, 5, 12, 7, 9, 9, 12, 12, 9, 7]
col2=[3.0, 0.5, 1.0, 1.0, 0.5, 0.5, 1.0, 0.5, 1.0, 3.0, 3.0, 3.0]
这些组合的结果的第三列:
col3=[1.435078, 1.161110, 3.012732, 1.341047, 1.299615, 2.718960, 3.913285, 2.064090, 1.261958, 1.158850, 3.079639, 2.579303]
我要提供的数据是表的左侧具有单独的column2值,表上方具有第1列的值,而第3列的值与两个因子的交集处显示的因子的每个唯一组合有关。 理想情况下,看起来应该像这样:
| | 5 | 7 | 9 | 12 |
|-----|------|------|------|------|
| 0.5 | 1.16 | 2.72 | 3.91 | 1.30 |
| 1.0 | 1.34 | 3.01 | 2.06 | 1.26 |
| 3.0 | 1.43 | 2.58 | 3.08 | 1.16 |
我需要使用什么函数来生成这种简单的数据可视化? 我已经尝试过table()
, xtab()
, list()
以及其他,但是经过数小时的xtab()
,我似乎无法弄清楚。
使用xtabs
:
xt <- xtabs(col3 ~ col2 + col1)
给予:
> xt
col1
col2 5 7 9 12
0.5 1.161110 2.718960 2.064090 1.299615
1 1.341047 3.012732 3.913285 1.261958
3 1.435078 2.579303 3.079639 1.158850
或使用ftable(xt)
获得稍微不同的输出。
tapply
也可以替代xtabs
:
tapply(col3, data.frame(col2, col1), c)
如果要在单元格周围划线,请尝试:
library(Hmisc)
print.char.matrix(xt, col.names = TRUE)
给予:
+----+--------+--------+--------+--------+
|col2| 5 | 7 | 9 | 12 |
+----+--------+--------+--------+--------+
| 0.5| 1.16111| 2.71896| 2.06409|1.299615|
+----+--------+--------+--------+--------+
| 1|1.341047|3.012732|3.913285|1.261958|
+----+--------+--------+--------+--------+
| 3|1.435078|2.579303|3.079639| 1.15885|
+----+--------+--------+--------+--------+
可复制形式的输入为:
col1 <- c(5, 5, 7, 5, 12, 7, 9, 9, 12, 12, 9, 7)
col2 <- c(3.0, 0.5, 1.0, 1.0, 0.5, 0.5, 1.0, 0.5, 1.0, 3.0, 3.0, 3.0)
col3 <- c(1.435078, 1.161110, 3.012732, 1.341047, 1.299615, 2.718960, 3.913285,
2.064090, 1.261958, 1.158850, 3.079639, 2.579303)
使用dplyr
和knitr
:
df %>%
spread(col1, col3) %>%
kable()
| col2| 5| 7| 9| 12|
|----:|--------:|--------:|--------:|--------:|
| 0.5| 1.161110| 2.718960| 2.064090| 1.299615|
| 1.0| 1.341047| 3.012732| 3.913285| 1.261958|
| 3.0| 1.435078| 2.579303| 3.079639| 1.158850|
或者只是使用dplyr
:
df %>%
spread(col1, col3)
col2 5 7 9 12
1 0.5 1.161110 2.718960 2.064090 1.299615
2 1.0 1.341047 3.012732 3.913285 1.261958
3 3.0 1.435078 2.579303 3.079639 1.158850
或使用reshape2
:
dcast(df, col2 ~ col1, value.var = "col3")
col2 5 7 9 12
1 0.5 1.161110 2.718960 2.064090 1.299615
2 1.0 1.341047 3.012732 3.913285 1.261958
3 3.0 1.435078 2.579303 3.079639 1.158850
数据:
df <- as.data.frame(cbind(col1 = c(5, 5, 7, 5, 12, 7, 9, 9, 12, 12, 9, 7),
col2 = c(3.0, 0.5, 1.0, 1.0, 0.5, 0.5, 1.0, 0.5, 1.0, 3.0, 3.0, 3.0),
col3 = c(1.435078, 1.161110, 3.012732, 1.341047, 1.299615, 2.718960, 3.913285, 2.064090, 1.261958, 1.158850, 3.079639, 2.579303)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.