Se Ko
Se Ko

Reputation: 47

R: How can I aggregate rows under conditions?

I'm trying to aggregate the variable Schulbildung which are less then 12. And aggregate the value of n. I tried using the aggregate() function but it didn't work. Has somebody any idea?

enter image description here

Upvotes: 1

Views: 93

Answers (1)

DSGym
DSGym

Reputation: 2867

Use mutate with an ifelse statement to recode every value that is smaller than 12. Summarise then with dplyr.

 df <- data.frame(
      Education = c(18, 16, 15, 12, 10, 8),
      entries = c(200, 100, 50, 50, 10 ,5)
    )

You said Education is a grouping varibale, so this means this is not the original data.frame, right?

df %>%
  ungroup() %>%
  mutate(Education = ifelse(Education < 12, "others", Education)) %>%
  group_by(Education) %>%
  summarise(entries = sum(entries))

Upvotes: 1

Related Questions