【问题标题】:How to separate a column by first digit如何按第一个数字分隔列
【发布时间】:2020-07-31 07:33:15
【问题描述】:

假设我们有一个如下所示的数据框:

name_and_age
Wesley Wycombe27 y.o.
Sally Atkinson33 y.o.
Matthew Lee42 y.o.

我想将其分成两列,将数据框设置为如下所示:

name                   age
Wesley Wycombe         27
Sally Atkinson         33
Matthew Lee            42

到目前为止,我一直在尝试使用separate()extract(),同时使用[:digit:]\\d 作为正则表达式,但是我所有的尝试都没有成功。

【问题讨论】:

    标签: r regex tidyr stringr


    【解决方案1】:

    我们可以使用extract 将字符捕获为一个组。在这里,我们指定模式以匹配从字符串开头 (^) 开始的一个或多个非数字字符 ([^0-9]+),捕获为一组 ((...)),后跟数字作为第二组和不捕获其余字符 (.*)

    library(dplyr)
    library(tidyr)
    df1 %>%
       extract(name_and_age, into = c('name', 'age'),
                '^([^0-9]+)(\\d+).*', convert = TRUE)
    #           name age
    #1 Wesley Wycombe  27
    #2 Sally Atkinson  33
    #3    Matthew Lee  42
    

    数据

    df1 <- structure(list(name_and_age = c("Wesley Wycombe27 y.o.", 
             "Sally Atkinson33 y.o.", 
    "Matthew Lee42 y.o.")),
    class = "data.frame", row.names = c(NA, 
    -3L))
    

    【讨论】:

      猜你喜欢
      • 2021-03-01
      • 1970-01-01
      • 2017-10-15
      • 1970-01-01
      • 1970-01-01
      • 2020-02-04
      • 1970-01-01
      • 2013-05-03
      • 1970-01-01
      相关资源
      最近更新 更多