HelpNeeded3
HelpNeeded3

Reputation: 91

How to calculate conditional average in data frame in R?

Suppose we have a data set, a snippet looks like:

count  party  gender
0      Rep    F
2      Rep    M
3      Rep    F

I'm trying to calculate the average value of the count column if party = Rep and gender = F. I.e. it should be 1.5 here. How can this be written in R code?

Upvotes: 1

Views: 865

Answers (3)

JDG
JDG

Reputation: 1364

Using data.table:

setDT(dt)
dt[, mean(count), .(party, gender)]

Output:

   party gender  V1
1:   Rep      F 1.5
2:   Rep      M 2.0

This will calculate the mean of count for all party-gender pairs, in the case that you want to include all combinations (not just only Rep/F).

Data:

dt = read.table(text = 'count  party  gender
0      Rep    F
2      Rep    M
3      Rep    F
', header = T)

Upvotes: 0

mel
mel

Reputation: 105

If you want to use base R:

mean(df[(df$party == 'Rep' & df$gender == 'F'),]$count)

Upvotes: 1

Karthik S
Karthik S

Reputation: 11584

Does this work:

library(dplyr)
dat %>% filter(party == 'Rep' & gender == 'F') %>% summarise(avg = mean(count))
# A tibble: 1 x 1
    avg
  <dbl>
1   1.5

Upvotes: 3

Related Questions