rstatistics

Counting function in R


I have a dataset like this

id <- 1:12
b <- c(0,0,1,2,0,1,1,2,2,0,2,2)
c <- rep(NA,3)
d <- rep(NA,3)

df <-data.frame(id,b)
newdf <- data.frame(c,d)

I want to do simple math. If x==1 or x==2 count them and write how many 1 and 2 are there in this dataset. But I don't want to count whole dataset, I want my function count them four by four.

I want to a result like this:

> newdf
  one two
1   1   1
2   2   1
3   0   3

I tried this with lots of variation but I couldn't success.

afonk <- function(x) {
  ifelse(x==1 | x==2, x, newdf <- (x[1]+x[2]))
} 

afonk(newdf$one)

lapply(newdf, afonk)

Thanks in advance!


Solution

  • Fun with base R:

    # counting function
    countnum <- function(x,num){
      sum(x == num)
    }
    
    # make list of groups of 4
    df$group <- rep(1:ceiling(nrow(df)/4),each = 4)[1:nrow(df)]
    dfl <- split(df$b,f = df$group)
    
    # make data frame of counts
    newdf <- data.frame(one = sapply(dfl,countnum,1),
                        two = sapply(dfl,countnum,2))
    

    Edit based on comment:

    # make list of groups of 4
    df$group <- rep(1:ceiling(nrow(df)/4),each = 4)[1:nrow(df)]
    
    table(subset(df, b != 0L)[c("group", "b")])
    

    Which you prefer depends on what type of result you need. A table will work for a small visual count, and you can likely pull the data out of the table, but if it is as simple as your example, you might opt for the data.frame.