I have a dataset in R
that contains a column that contains a string that I want to separate into multiple columns using separate_wider_delim from the tidyr
package.
What I want to do is to pad the column names so that they will always result in a number that is 2 digits (ie. ’01’ instead of ‘1’).
However, the resulting dataframe had the new column names ending in a single digit number.
Does anyone know how to implement number padding in separate_wider_delim?
Below is an example code to demonstrate what I currently am trying and my desired output.
Code:
library(tidyr)
#data
df <- data.frame(Group = c("A","B","C"),
fruits_selected = c(
"'Apple'+'Banana'+'Cherry'",
"'Peach'+'Banana'+'Apple'",
"'Orange'+'Banana'+'Cherry'")
)
#Separate the vectors in the "fruits_selected" column into multiple columns
df2 <- df %>%
separate_wider_delim(fruits_selected, delim="+", names_sep = "_")
Current output:
#Current output of the result
print(df2)
#> Group fruits_selected_1 fruits_selected_2 fruits_selected_3
#> <chr> <chr> <chr> <chr>
#> 1 A 'Apple' 'Banana' 'Cherry'
#> 2 B 'Peach' 'Banana' 'Apple'
#> 3 C 'Orange' 'Banana' 'Cherry'
Desired Output:
print(df2)
#> Group fruits_selected_01 fruits_selected_02 fruits_selected_03
#> <chr> <chr> <chr> <chr>
#> 1 A 'Apple' 'Banana' 'Cherry'
#> 2 B 'Peach' 'Banana' 'Apple'
#> 3 C 'Orange' 'Banana' 'Cherry'
Thank you so much for your assistance!