toString() or something else with a condition

Suppose I have the following table

x
1
2
3
4
5
6
7
8

I am trying to mutate wanted, which will store the values of x separated by comma. Note that wanted can contain maximum three numbers (wanted will have only one row if x has three rows).

wanted
1, 2, 3
4, 5, 6
7, 8
library(dplyr)
# toy data
df <- tibble(x  = 1:8)

Like this?

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
# toy data
df <- tibble(x  = 6:13)
df1 <- df |>
  mutate(linenr = 1 + (row_number()-1)%/%3)|>
  nest_by(linenr,.key="data") |>
  mutate( wanted = paste(data$x,collapse=',')) |>
  ungroup() |>
  select(-c(linenr,data))  |>
  print()
#> # A tibble: 3 x 1
#>   wanted 
#>   <chr>  
#> 1 6,7,8  
#> 2 9,10,11
#> 3 12,13
Created on 2021-12-13 by the reprex package (v2.0.1)
1 Like

@HanOostdijk Thanks! It does solve my problem.

Here´s another way

library(dplyr)
# toy data
df <- tibble(x  = 1:8)

df %>%
  group_by((row_number() - 1) %/% 3) %>% # 3 -> your max-groupsize
  summarise(wanted = toString(x)) %>%
  select(wanted)

#> # A tibble: 3 × 1
#>   wanted 
#>   <chr>  
#> 1 1, 2, 3
#> 2 4, 5, 6
#> 3 7, 8

Created on 2021-12-15 by the reprex package (v2.0.1)

1 Like

@macjo16 Many thanks for the neat solution!

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.