Say I have a csv file containing this sort of data from the tidyr documentation:
df <- data.frame(x = c("a.b", "a.d", "b.c"))
df %>% separate(x, c("A", "B"))
A B
1 a b
2 a d
3 b c
This works great if you know how many columns will be in your output. In my case, I'm connecting this dataset to a shinydashboard that dynamically generates a plot based on this data.
I'd like to separate the column x into different columns by a separator . and dynamically generate custom column names along the way. Something I had in mind:
df %>% separate(col = x,
into = paste0("x_", 1:2))
x_1 x_2
1 a b
2 a d
3 b c
but I'd like the numbers coming after _ to be reactively generated depending on the number of columns x is separated into.
suppressPackageStartupMessages({
library(tidyr)
library(stringr)
})
begin <- letters
finish <- rev(letters)
var <- paste0(begin,".",finish)
df_ <- data.frame(x = var)
out_length <- length(str_split(df_[1,1],"\\.")[[1]])
df_ %>% separate(col = x,
into = paste0("x_", 1:out_length))
#> x_1 x_2
#> 1 a z
#> 2 b y
#> 3 c x
#> 4 d w
#> 5 e v
#> 6 f u
#> 7 g t
#> 8 h s
#> 9 i r
#> 10 j q
#> 11 k p
#> 12 l o
#> 13 m n
#> 14 n m
#> 15 o l
#> 16 p k
#> 17 q j
#> 18 r i
#> 19 s h
#> 20 t g
#> 21 u f
#> 22 v e
#> 23 w d
#> 24 x c
#> 25 y b
#> 26 z a
Created on 2020-10-27 by the reprex package (v0.3.0.9001)