How to grouped data assigned as 0 or 1?

Viewed 103

I want to group the dataset by name and if the same name includes at least one 0 in the response column, I want to assign it as 0 else 1. Please see the data and output.

   data = data.frame(stringsAsFactors = FALSE,
                      name = c("Mary", "Frank", "Tom", "Frank", "Mary"),
                      response = c(1, 0, 1, 0, 0))

For instance, Mary's response values are 0 and 1, so I will assign it as 0. See the output below.

Output = data.frame(stringsAsFactors = FALSE,
                  name = c("Mary", "Frank", "Tom"),
                  response = c(0, 0, 1))
3 Answers

You can take minimum value of response variable.

library(dplyr)
data %>%
  group_by(name) %>%
  summarise(response = min(response))

Or this maybe more clear :

data %>%
  group_by(name) %>%
  summarise(response = if(any(response == 0)) 0 else 1)

In base R, using aggregate :

aggregate(response~name, data, min)

We can use data.table

library(data.table)
setDT(data)[, .(response = if(0 %in% response) 0  else 1), name]

Or this

library(dplyr)
data %>%
  group_by(name) %>%
  summarise(response = prod(response))

prod will make summarised value 0 if at least one 0 is there else it'll return 1 only.

Similarly in baseR

aggregate(response~name, data, prod)

   name response
1 Frank        0
2  Mary        0
3   Tom        1
Related