简体   繁体   中英

How to count conditional occurence in R?

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 !

How about 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

Here is another alternative (also using 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

Update

Here's a "reshape2" approach:

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

Update 2

(To represent base R again)...

Building on @SimonO101's solution, here's a more automated way:

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

You can use count from plyr package.

?count:

Equivalent to as.data.frame(table(x)), but does not include combinations with zero counts

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM