Add column to grouped data that assigns 1 to individuals and randomly assigns 1 or 0 to pairs

Viewed 102

I have a dataframe...

df <- tibble(
  id = 1:7, 
  family = c("a","a","b","b","c", "d", "e")
  )

Families will only contain 2 members at most (so they're either individuals or pairs).

I need a new column 'random' that assigns the number 1 to families where there is only one member (e.g. c, d and e) and randomly assigns 0 or 1 to families containing 2 members (a and b in the example).

By the end the data should look like the following (depending on the random assignment of 0/1)...

df <- tibble(
  id = 1:7, 
  family = c("a","a","b","b","c", "d", "e"),
  random = c(1, 0, 0, 1, 1, 1, 1)
  )

I would like to be able to do this with a combination of group_by and mutate since I am mostly using Tidyverse.

I tried the following (but this didn't randomly assign 0/1 within families)...

df %>%
group_by(family) %>%
  mutate(
   random = if_else(
     condition = n() == 1,
     true = 1,
     false = as.double(sample(0:1,1,replace = T))
   )
3 Answers

You could sample along the sequence length of the family group and take the answer modulo 2:

df %>% 
  group_by(family) %>% 
  mutate(random = sample(seq(n())) %% 2)
#> # A tibble: 7 x 3
#> # Groups:   family [5]
#>      id family random
#>   <int> <chr>   <dbl>
#> 1     1 a           0
#> 2     2 a           1
#> 3     3 b           0
#> 4     4 b           1
#> 5     5 c           1
#> 6     6 d           1
#> 7     7 e           1


We can use if/else

library(dplyr)
df %>% 
  group_by(family) %>%
  mutate(random = if(n() == 1) 1 else sample(rep(0:1, length.out = n())))
# A tibble: 7 x 3
# Groups:   family [5]
#     id family random
#  <int> <chr>   <dbl>
#1     1 a           0
#2     2 a           1
#3     3 b           1
#4     4 b           0
#5     5 c           1
#6     6 d           1
#7     7 e           1

Another option

df %>%
  group_by(family) %>%
  mutate(random = 2 - sample(1:n()))

# A tibble: 7 x 3
# Groups:   family [5]
     id family random
#   <int> <chr>   <dbl>
# 1     1 a           1
# 2     2 a           0
# 3     3 b           1
# 4     4 b           0
# 5     5 c           1
# 6     6 d           1
# 7     7 e           1
Related