重塑数据帧

时间:2015-03-18 16:40:43

标签: r plyr dplyr reshape2

我有一个像这样的数据框:

col1  col2  year  mean  median
a     c     2012  14.9  14
a     c     2013  12.1  13 
r     d     2012  11.0  11
r     d     2013  13.1  15

我想将其转换为:

               2012            2013
col1  col2  mean  median    mean  median
a     c     14.9  14        12.1  13
r     d     11.0  11        13.1  15 

4 个答案:

答案 0 :(得分:1)

您可以尝试reshape

reshape(df1, idvar=c('col1', 'col2'), timevar='year',  direction='wide')
#     col1 col2 mean.2012 median.2012 mean.2013 median.2013
#1    a    c      14.9          14      12.1          13
#3    r    d      11.0          11      13.1          15

数据

df1 <- structure(list(col1 = c("a", "a", "r", "r"), col2 = c("c", "c", 
"d", "d"), year = c(2012, 2013, 2012, 2013), mean = c(14.9, 12.1, 
11, 13.1), median = c(14L, 13L, 11L, 15L)), .Names = c("col1", 
"col2", "year", "mean", "median"), row.names = c(NA, -4L),
 class =   "data.frame")

答案 1 :(得分:1)

Dataframes无法保存2D列标题。见这里

https://stat.ethz.ch/R-manual/R-patched/library/base/html/colnames.html

对于数据框,rownames的值应该是非重复和非缺失名称的字符向量(这是强制执行的),并且对于colnames,是(最好)唯一语法有效名称的字符向量。在这两种情况下,值都将被as.character强制执行,设置colnames会将行名称转换为字符。

注意向量在R中是1D。这看起来更像是数据的Excel表示而不是R。如果你想过滤多年,那么你可以这样做:

d[d$year == 2012,]

假设您的数据框被称为d。如果您想删除年份列:

d[d$year == 2012, c(1,2,4,5)]

答案 2 :(得分:0)

data.table v1.9.5+开始,dcast可以处理多个value.var列。我们可以这样做:

require(data.table)
dcast(setDT(dat), col1 + col2 ~ year, value.var=c("mean", "median"))
#    col1 col2 2012_mean 2013_mean 2012_median 2013_median
# 1:    a    c      14.9      12.1          14          13
# 2:    r    d      11.0      13.1          11          15

其中dat是您的data.framesetDT()通过引用将其转换为data.table

您可以按照these instructions来获取它。

答案 3 :(得分:0)

如果您为未说明的操作系统安装Tex软件包,您可以使用tablesHmisc软件包提供更符合您要求的内容,因为表格函数能够提供两者 - 您指定的行标题:

require(tables); require(Hmisc)
val <- tabular( (Species + 1) ~ (n=1) + Format(digits=2)*(Sepal.Length + 
                                                  Sepal.Width)*(mean + sd), data=iris )
 Hmisc::latex(val, file="tbl.tex")

enter image description here

当预期目录中有pdflatex时,"tbl.tex"文件会传递给它,然后在我的系统上至少会以.dvi形式显示在名为Skim的pdfviewer中。我通过Preview.app将其导出为.png文件,您可以在上面看到它。您可以不指定tex文件并将Latex代码打印到R控制台:

Hmisc::latex(val)
\begin{tabular}{lccccc}
\hline
 &  & \multicolumn{2}{c}{Sepal.Length} & \multicolumn{2}{c}{Sepal.Width} \\ 
Species  & n & mean & sd & mean & \multicolumn{1}{c}{sd} \\ 
\hline
setosa  & $\phantom{0}50$ & $5.01$ & $0.35$ & $3.43$ & $0.38$ \\
versicolor  & $\phantom{0}50$ & $5.94$ & $0.52$ & $2.77$ & $0.31$ \\
virginica  & $\phantom{0}50$ & $6.59$ & $0.64$ & $2.97$ & $0.32$ \\
All  & $150$ & $5.84$ & $0.83$ & $3.06$ & $0.44$ \\
\hline 
\end{tabular}
> ?latex
> val <- tabular( (Species + 1) ~ (n=1) + Format(digits=2)*
+ (Sepal.Length + Sepal.Width)*(mean + sd), data=iris )

Hmisc中还有一个html函数,它将生成HTML表格代码。

相关问题