Separate string after last underscore

前端 未结 2 1718
攒了一身酷
攒了一身酷 2021-01-14 08:25

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

2条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-14 08:52

    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
    

提交回复
热议问题