[R] adding counter to df by group

Davide Piffer pifferdavide at gmail.com
Wed May 3 20:24:41 CEST 2017


I need to count the trials in an experiment, separately for each
subject. I thought about using the function "by" but I could not
manage to achieve this. Instead, I tried "split" and I got closer to a
solution but still not getting there yet.
The following code should create a variable "miniblock" with the
trial/miniblock number.
split_cong=split(red_congruent,red_congruent$subject_nr)
miniblock_cong=lapply(split_cong,seq_along)
red_congruent$miniblock=unlist(miniblock_cong)

However, I get the following error message: Error in
`$<-.data.frame`(`*tmp*`, "miniblock", value = c(1L, 2L, 3L,  :
  replacement has 460 rows, data has 500

Is there a more efficient way to achieve the result? Maybe with "by" or dplyr?

Thanks a lot in advance!



More information about the R-help mailing list