Summarize and count data in R with dplyr

前端 未结 1 519
温柔的废话
温柔的废话 2021-01-26 12:38

Goal: Summarize/count responses in the same row of an occured stimuli with dplyr.

Background: I got some excellent help in another topic: Loop

1条回答
  •  梦毁少年i
    2021-01-26 13:06

    Here is a two line solution in base R. First, create an ID that is unique to each user-(new)stimulus combination. This is accomplished with paste and cumsum.

    dat$stims <- with(dat, paste(cumsum(StimuliA), cumsum(StimuliB), sep="_"))
    

    Then use aggregate to calculate the responses for each of the new IDs

    aggregate(. ~ User + stims, data=dat, sum)
      User stims StimuliA StimuliB R2 R3 R4 R5 R6 R7
    1    1   1_0        1        0  0  0  0  0  0  1
    2    1   2_0        1        0  1  1  0  0  1  0
    3    1   2_1        0        1  1  2  0  0  1  0
    4    1   2_2        0        1  0  0  0  0  0  0
    5    2   3_2        1        0  3  0  0  0  0  0
    6    2   3_3        0        1  1  0  0  0  2  0
    

    0 讨论(0)
提交回复
热议问题