Count how many times a value has appeared in a vector [with conditions in R] -


i have following dataset , count how many times in vector condition has occured:

structure(list(id = c(1l, 1l, 1l, 1l, 2l, 2l, 2l, 2l, 3l, 3l,  3l, 3l), stimuli = c(1l, 0l, 0l, 1l, 1l, 1l, 0l, 1l, 0l, 1l,  0l, 1l)), .names = c("id", "stimuli"), class = c("tbl_df", "tbl",  "data.frame"), row.names = c(na, -12l), spec = structure(list(     cols = structure(list(id = structure(list(), class =  c("collector_integer",      "collector")), stimuli = structure(list(), class = c("collector_integer",      "collector"))), .names = c("id", "stimuli")), default = structure(list(), class = c("collector_guess",      "collector"))), .names = c("cols", "default"), class = "col_spec")) 

only counting every id seperatly , if value of stimuli has been 1. result summarized in row , this:

id  stimuli count 1      1    1 1      0    0 1      0    0 1      1    2 2      1    1 2      1    2 2      0    0 2      1    3 3      0    0 3      1    1 3      0    0 3      1    2 

i aware of as.data.frame(table(df)) getting frequency, in case keep every row , count in every id-sequence.

you can use data.table package:

 library(data.table)  setdt(df)[, count := cumsum(stimuli)*stimuli, by=id]   #     id stimuli count  #  1:  1       1     1  #  2:  1       0     0  #  3:  1       0     0  #  4:  1       1     2  #  5:  2       1     1  #  6:  2       1     2  #  7:  2       0     0  #  8:  2       1     3  #  9:  3       0     0  # 10:  3       1     1  # 11:  3       0     0  # 12:  3       1     2 

Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -