本文介绍了创建数据透视表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个数据集,如下所示,其中年份在各行中列出:
Suppose I have a dataset that looks like the following, in which years are listed down rows:
id<-c(1,1,1,2,2,2,3,3,3)
year<-c(1990, 1991, 1992, 1992, 1993, 1994, 1993, 1994, 1995)
N<-c(7,8,9,7,1,2,5,4,3)
dataset<-data.frame(cbind(id, year, N))
我希望输出如下所示,以年份作为列标题:
I'd like to have the output look like the following, with years as column headings:
id 1990 1991 1992 1993 1994 1995
1 7 8 9 0 0 0
2 0 0 7 1 2 0
3 0 0 0 5 4 3
我知道这是一个相当简单的问题,但是我一直在搞乱xtabs(),melt()和cast(),但我不太清楚.
I know this is a fairly easy problem, but I've been messing around with xtabs() and with melt() and cast(), but I can't quite get it right.
推荐答案
另一种方法:
> library(reshape2)
> dcast(dataset, id ~ year, fill=0)
# Using N as value column: use value.var to override.
id 1990 1991 1992 1993 1994 1995
1 1 7 8 9 0 0 0
2 2 0 0 7 1 2 0
3 3 0 0 0 5 4 3
这篇关于创建数据透视表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!