Separate a column into 2 columns at the last underscore in R

前端 未结 1 1259
借酒劲吻你
借酒劲吻你 2021-01-12 06:29

I have a dataframe like this

id <-c(\"1\",\"2\",\"3\")
col <- c(\"CHB_len_SCM_max\",\"CHB_brf_SCM_min\",\"CHB_PROC_S_SV_mean\")

df <- data.frame(i         


        
相关标签:
1条回答
  • 2021-01-12 06:53

    We could use extract by capturing as two groups by making sure that the second group have one or more characters that are not a _ until the end ($) of the string

    library(tidyverse)
    df %>% 
       extract(col, into = c("Measurement", "stat"), "(.*)_([^_]+)$")
    #   id   Measurement stat
    #1  1   CHB_len_SCM  max
    #2  2   CHB_brf_SCM  min
    #3  3 CHB_PROC_S_SV mean
    

    Or using separate with a regex lookaround

    df %>% 
       separate(col, into = c("Measurement", "stat"), sep="_(?=[^_]+$)")
    
    0 讨论(0)
提交回复
热议问题