2

I have a set of data :

Color Type axe

Green  1    2

Green  1    3

Green  0    1

Black  1    1

Black  0    2

Black  0    3

I want to return a table that tells me how many time a 'Type' is green or black and a 'axe' is green or black.

Type 

1   Green : 2 Black : 1

0   Green : 1 Black : 2

Axe

1   Green : 1 Black : 1

2   Green : 1 Black : 1

3   Green : 1 Black : 1

So a conditional count. I wanted to use the function 'table', but it just does a column occurrence count.

Thanks !

4

3 回答 3

3

怎么样table

table( dat[ , c("Color" , "Type") ] )
       Type
Color   0 1
  Black 2 1
  Green 1 2

table( dat[ , c("Color" , "axe") ] )
       axe
Color   1 2 3
  Black 1 1 1
  Green 1 1 1
于 2013-08-16T16:11:55.203 回答
2

这是另一种选择(也使用table):

table(cbind(mydf[1], stack(mydf[-1])))
# , , ind = axe
# 
#        values
# Color   0 1 2 3
#   Black 0 1 1 1
#   Green 0 1 1 1
# 
# , , ind = Type
# 
#        values
# Color   0 1 2 3
#   Black 2 1 0 0
#   Green 1 2 0 0

更新

这是一种“reshape2”方法:

library(reshape2)
x <- melt(mydf)
# Using Color as id variables
y <- dcast(x, value + variable ~ Color)
# Aggregation function missing: defaulting to length
split(y[-2], y[[2]])
# $Type
#   value Black Green
# 1     0     2     1
# 2     1     1     2
# 
# $axe
#   value Black Green
# 3     1     1     1
# 4     2     1     1
# 5     3     1     1

更新 2

(再次代表基数 R)...

基于@SimonO101 的解决方案,这是一种更自动化的方法:

idvar <- "Color"
lapply(setdiff(names(mydf), idvar), function(y) table(mydf[, c(idvar, y)]))
# [[1]]
#        Type
# Color   0 1
#   Black 2 1
#   Green 1 2
# 
# [[2]]
#        axe
# Color   1 2 3
#   Black 1 1 1
#   Green 1 1 1
于 2013-08-16T16:19:32.287 回答
0

您可以countplyr包中使用。

?count:

等效于 as.data.frame(table(x)),但不包括计数为零的组合

library(plyr)
count(da,c('Color','Type'))

 Color Type freq
1 Black    0    2
2 Black    1    1
3 Green    0    1
4 Green    1    2
于 2013-08-16T16:22:59.377 回答