neòinean
neòinean

Reputation: 39

R: Split all groups in half (dplyr)

My data is grouped, but I would like to split each group in two, as illustrated in the example below. It doesn't really matter what the content of group_half will be, it can be anything like 1a/1b or 1.1/1.2. Any recommendations on how to do this using dplyr? Thanks!

col_1 <- c(23,31,98,76,47,65,23,76,3,47,54,56)
group <- c(1,1,1,1,2,2,2,2,3,3,3,3)

group_half <- c(1.1, 1.1, 1.2, 1.2, 2.1, 2.1, 2.2, 2.2, 3.1, 3.1, 3.2, 3.2)
df1 <- data.frame(col_1, group, group_half)

# col_1   group   group_half
#    23       1          1.1
#    31       1          1.1
#    98       1          1.2
#    76       1          1.2
#    47       2          2.1
#    65       2          2.1
#    23       2          2.2
#    76       2          2.2
#     3       3          3.1
#    47       3          3.1
#    54       3          3.2
#    56       3          3.2

Upvotes: 0

Views: 268

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388982

Here are two options :

  1. If you always have even number of rows in each group.
library(dplyr)

df1 %>% 
  group_by(group) %>% 
  mutate(group_half = paste(group, rep(1:2, each = n()/2), sep = '.')) %>% 
  ungroup

#   col_1 group group_half
#   <dbl> <dbl> <chr>     
# 1    23     1 1.1       
# 2    31     1 1.1       
# 3    98     1 1.2       
# 4    76     1 1.2       
# 5    47     2 2.1       
# 6    65     2 2.1       
# 7    23     2 2.2       
# 8    76     2 2.2       
# 9     3     3 3.1       
#10    47     3 3.1       
#11    54     3 3.2       
#12    56     3 3.2       
  1. This will work irrespective of number of rows in the group.
df1 %>%
  group_by(group) %>%
  mutate(group_half = paste(group,as.integer(row_number() > n()/2) + 1, sep = '.')) %>% 
  ungroup

Upvotes: 1

Related Questions