R:将行值转换为列名并计算其指定值

时间:2013-06-12 05:28:05

标签: r

我有一个如下所示的数据框:

data.frame(name=c("a","a","b","b","c"),
value=c("2011-01-23","2011-01-23","2011-01-23","2011-01-22","2011-01-22"))

name     value
 a        2011-01-23
 a        2011-01-23
 b        2011-01-23
 b        2011-01-22
 c        2011-01-22

我只有3个不同的名字,我想把它变成:

a    b   c   date
2    1   0    2011-01-23
0    1   1    2011-01-22

我查看了reshape包,但我无法理解文档,以解决这个问题。

2 个答案:

答案 0 :(得分:3)

假设您的data.framedat,并使用dcast()中的reshape2

dcast(dat, value ~ name)

#        value a b c
# 1 2011-01-22 0 1 1
# 2 2011-01-23 2 1 0

答案 1 :(得分:0)

看看tablet(table(dat))应该这样做(如果您的源对象名为“dat”)。将整个语句包含在as.data.frame.matrix(.)中以获得data.frame

t(table(dat))
#             name
# value        a b c
#   2011-01-22 0 1 1
#   2011-01-23 2 1 0
as.data.frame.matrix(t(table(dat)))
#            a b c
# 2011-01-22 0 1 1
# 2011-01-23 2 1 0