与R(plyr,ddplyr?)一样的Excel数据透视表功能

时间:2015-04-14 13:11:19

标签: r plyr dplyr reshape reshape2

我希望使用R比使用Excel更快地创建数据透视表(并减少错误空间。

例如,如果我有这样的数据集:

id<-c("p","q","r","s","t","u","p","q","r","s","t","u")
time<-c(0,0,0,0,0,0,1,1,1,1,1,1)
foldchange<-rnorm(12)
log2foldchange<-rnorm(12)
p.value<-rnorm(12)
df<-data.frame(id,time,foldchange,log2foldchange,p.value)

我希望按照excel使用数据透视表看起来像这样(或尽可能接近)来排序表格: enter image description here

有什么想法吗?从这里的例子中无法弄清楚如何做到这一点(或类似于此的任何事情)。

谢谢!

3 个答案:

答案 0 :(得分:4)

如果要为示例

生成随机数,则应set.seed
set.seed(1)
id<-c("p","q","r","s","t","u","p","q","r","s","t","u")
time<-c(0,0,0,0,0,0,1,1,1,1,1,1)
foldchange<-rnorm(12)
log2foldchange<-rnorm(12)
p.value<-rnorm(12)
df<-data.frame(id,time,foldchange,log2foldchange,p.value)


reshape(df, dir = 'wide', idvar = 'id', timevar = 'time')

#   id foldchange.0 log2foldchange.0   p.value.0 foldchange.1 log2foldchange.1   p.value.1
# 1  p   -0.6264538      -0.62124058  0.61982575    0.4874291       0.82122120  1.35867955
# 2  q    0.1836433      -2.21469989 -0.05612874    0.7383247       0.59390132 -0.10278773
# 3  r   -0.8356286       1.12493092 -0.15579551    0.5757814       0.91897737  0.38767161
# 4  s    1.5952808      -0.04493361 -1.47075238   -0.3053884       0.78213630 -0.05380504
# 5  t    0.3295078      -0.01619026 -0.47815006    1.5117812       0.07456498 -1.37705956
# 6  u   -0.8204684       0.94383621  0.41794156    0.3898432      -1.98935170 -0.41499456

或只是

reshape(df, dir = 'wide')

#   id foldchange.0 log2foldchange.0   p.value.0 foldchange.1 log2foldchange.1   p.value.1
# 1  p   -0.6264538      -0.62124058  0.61982575    0.4874291       0.82122120  1.35867955
# 2  q    0.1836433      -2.21469989 -0.05612874    0.7383247       0.59390132 -0.10278773
# 3  r   -0.8356286       1.12493092 -0.15579551    0.5757814       0.91897737  0.38767161
# 4  s    1.5952808      -0.04493361 -1.47075238   -0.3053884       0.78213630 -0.05380504
# 5  t    0.3295078      -0.01619026 -0.47815006    1.5117812       0.07456498 -1.37705956
# 6  u   -0.8204684       0.94383621  0.41794156    0.3898432      -1.98935170 -0.41499456

非常直截了当,对@ data.table?

答案 1 :(得分:2)

使用data.table v1.9.5,这非常简单:

require(data.table) # v1.9.5+
dcast(setDT(df), id ~ time, value.var = names(df)[3:5])

PS:我假设p值仅仅是为了它...因为它们是-ve /&gt;你应该从均匀分布中生成随机值。

答案 2 :(得分:0)

使用不太直观的dplyrtidyr

library(dplyr); library(tidyr)
df %>% gather(name, value, c(-id, -time)) %>% mutate(new=paste(name, time, sep=".")) %>% 
  select(-time, -name) %>% spread(new, value)

逻辑如下:

foldchange的数据转置为p.value 这是通过代码df %>% gather(name, value, c(-id, -time))完成的。

接下来在excel中将您想要拥有的变量连接为column labels,这是通过mutate(new=paste(name, time, sep="."))部分完成的

最后通过首先选择您感兴趣的列的spread(new, value)来转置连接变量。

根据您的排序方式(列),您也可以尝试

df %>% gather(name, value, c(-id, -time)) %>% mutate(new=paste(time, name, sep=".")) %>% 
  select(-time, -name) %>% spread(new, value)

差异为mutate(new=paste(time, name, sep="."))