用于查找" R"中的对的频率。

时间:2014-07-28 00:58:31

标签: r casting aggregate-functions

如果我有以下数据:

id <- c(1,2,3,4,5,3,5,4)
type <- c(1,2,2,3,1,3,2,2)
df <- data.frame(id,type)

  id type
1  1    1
2  2    2
3  3    2
4  4    3
5  5    1
6  3    3
7  5    2
8  4    2

假设我想得到每个(id,type)的频率计数,以便得到以下数据帧。

df.want <- data.frame(id = c(1,2,3,4,5),x.1 = c(1,0,0,0,1),x.2 = c(0,1,1,1,1),x.3 = c(0,0,1,1,0))

df.want

  id x.1 x.2 x.3
1  1   1   0   0
2  2   0   1   0
3  3   0   1   1
4  4   0   1   1
5  5   1   1   0

因此,对于每个ID,我希望每种类型的频率为一行。我试过了cast(df,id ~ type,summary),但得到了:

Using type as value column.  Use the value argument to cast to override this choice
Error in `[.data.frame`(data, , variables, drop = FALSE) : 
  undefined columns selected

我想我可能会很亲密。有什么想法吗?

3 个答案:

答案 0 :(得分:3)

这基本上是table操作:

as.data.frame.matrix(table(df))

#  1 2 3
#1 1 0 0
#2 0 1 0
#3 0 1 1
#4 0 1 1
#5 1 1 0

答案 1 :(得分:0)

试试这个:

> xtabs(data = df)
   type
id  1 2 3
  1 1 0 0
  2 0 1 0
  3 0 1 1
  4 0 1 1
  5 1 1 0

答案 2 :(得分:0)

使用reshape

library(reshape)
df$type1 <- 1
cast(df, id~type,value="type1",fill=0)
#     id 1 2 3
#   1  1 1 0 0
#   2  2 0 1 0
#   3  3 0 1 1
#   4  4 0 1 1
#   5  5 1 1 0