This is indeed a duplicate for this question r-split-string-using-tidyrseparate, but I cannot use the MWE for my purpose, because I do not know how to adjust the regular Ex
Here's an alternative data.table solution using tstrsplit
/melt
/dcast
I would personally stick with data.table
in this case because spread
doesn't have a fun
argument, hence, if you have dupes when spreading again, you will get an error.
library(magrittr) # people like pipes these days
dt %>%
# convert ot long format like you did
melt(., id = "Name") %>%
# split by the last underscore
.[, c("variable", "grp") := tstrsplit(variable, "_(?!.*_)", perl = TRUE)] %>%
# convert back to wide format
dcast(., Name + grp ~ variable)
# Name grp Var_1 Var_2
# 1: A BdS NA NA
# 2: A EVU 2 NA
# 3: B BdS 3 3
# 4: B EVU NA NA
# 5: C BdS 4 4
# 6: C EVU NA NA