0

I have this dataframe

click me

and I want to find the total number of test group(exposed) when the purchased is 1

for (i in df$exposed) {
  if (i == "Test Group (Exposed)" && df$purchased == 1){
    
    print(i)

  }
} 

I'm not sure how to do it...

sdfweej009
  • 29
  • 4

1 Answers1

2

We generally use sum to count things - this is true in a lot of programming languages. TRUE is 1, FALSE is 0, so the sum of TRUE/FALSE values is the number of trues. In your case:

sum(df$exposed == "Test Group (Exposed)" & df$purchased == 1)

No for loop or print needed.

Similarly, you can use mean() to get the percent of TRUE values.

If you wanted to do this for groups (e.g., get the number of rows with 1 purchase for all the exposed categories) see the FAQ on how to sum a variable by groups.

Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294