How to add and subtract specific values from a frequency table in r?

60 Views Asked by At

This may have been asked before, but I couldn't find it. I have a data set and created a frequency table based on the data frame. I

It looks like this:

       outcome  N
    1    3      70
    2    1      8000
    3    4      212
    4    2      78

So lets say I want to add 8000 and 78 (outcomes 1 and 2). Is there a way to add/subtract these values from this frequency table?

1

There are 1 best solutions below

0
gurezende On

You can do it like this. library(tidyverse)

# Creating a toy dataframe
df <- data.frame(outcome = sample(1:4, 1000, replace=T))

# 1. Frequency Table
# 2. Group by outcome
# 3. Summarise count of each group
# 4. Create ifelse condition to transform 1 & 2 row to the same group
# 5. Group by the new group and sum counts.

df_freq <- df %>% 
  group_by(outcome) %>% 
  summarise(N = n()) %>% 
  mutate(add = ifelse(outcome < 3, '1 & 2', outcome)) %>% 
  group_by(add) %>% summarise(total = sum(N))

Result

   add    total
1  1 & 2  482
2  3      276
3  4      242