0

I'm trying now for some days to find a solution to something really simple, with no luck. Here it is:

  1. I've got a data frame with a row called RESPONSE.
  2. I'm subsetting condition A and then grouping by Subject.
  3. I'd like to count the sum of the cases per Subject where RESPONSE==44 and RESPONSE==77. However, not every subject has these, so for some subjects this sum should be 0.

I tried various commands, incl. summarise, count, filter. But I either get an aggregate of the cases overall for everyone, or it drops participants who don't have 77 or 44 (as opposed to assigning them a 0).

I imagine the code should look something like:

Condition_A <- subset(df, Condition=="A") %>%
  group_by(Subject) %>%
  sum(df$RESPONSE==77 | df$RESPONSE==44)

I see other people using sum the same way but I get an error that all my variables need to be numeric, and the row RESPONSE itself is. I'd be extremely grateful for any help here. Thank you.

1 Answer 1

1

Use summarise.

library(tidyverse)

df <- tribble(
  ~Condition, ~Subject, ~RESPONSE,
         "A",        1,        77,
         "A",        1,        44,
         "A",        1,         1,
         "A",        2,         1,
         "A",        2,         1,
         "A",        2,        44,
         "A",        3,         1
)

df %>%
  filter(Condition == "A") %>%
  group_by(Subject) %>%
  summarise(
    responses = sum(RESPONSE == 77 | RESPONSE == 44, na.rm = TRUE)
  )
#> # A tibble: 3 x 2
#>   Subject responses
#>     <dbl>     <int>
#> 1       1         2
#> 2       2         1
#> 3       3         0
Sign up to request clarification or add additional context in comments.

3 Comments

Unfortunately, I did everything exactly the same and I still get only 1x1 output, with a single value, summarised for all my participants. For some reason it just would not group by Subject. Do you have any possible suggestion?
It sounds like the summarise function from plyr is being used instead of dplyr. Replace summarise with dplyr::summarise.
Million thanks! That was exactly the problem! Have a lovely evening :))))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.