【问题标题】:R - gsub() for to remove dates from data setR - gsub() 用于从数据集中删除日期
【发布时间】:2017-12-09 10:01:08
【问题描述】:

我正在使用 gsub() 函数从数据中删除不需要的文本。我只想在括号中输入年龄,而不是出生日期。但是,这是在具有不同出生日期的大型数据集中。

数据示例:

Test1$Age

Sep 10, 1990(27)
Mar 26, 1987(30
Feb 24, 1997(20)

【问题讨论】:

  • gsub('\\(([0-9]+)\\)', '\\1', x)
  • 干杯迈克尔,但这只是删除括号
  • 哎呀,忘了我的.*

标签: r regex substring gsub


【解决方案1】:

您可以使用stringr 包中的str_extract() 执行此操作:

s <- "Sep 10, 1990(27)"

# get the age in parentheses
stringr::str_extract(s, "\\([0-9]+\\)")

# just the age, with parentheses removed
stringr::str_extract(s, "(?<=\\()[0-9]+")

输出是:

> s <- "Sep 10, 1990(27)"
> 
> # get the age in parentheses
> stringr::str_extract(s, "\\([0-9]+\\)")
[1] "(27)"
> 
> # just the age, with parentheses removed
> stringr::str_extract(s, "(?<=\\()[0-9]+")
[1] "27"

第一个正则表达式匹配包含一个或多个数字的成对括号。第二个正则表达式使用positive lookbehind 匹配左括号后面的一个或多个数字。

如果您的数据在 data.frame df 中,列名为 age,那么您可以执行以下操作:

df$age <- stringr::str_extract(df$age, "\\([0-9]+\\)")

或者,用tidyverse 表示法:

df <- df %>% mutate(age = stringr::str_extract(age, "\\([0-9]+\\)"))

【讨论】:

    【解决方案2】:

    好像有两个问题:

    1. 不需要左括号之前的日期
    2. 右括号有时会丢失,需要插入

    1) sub 可以使用sub 解决这些问题。匹配

    • 任意数量的字符.* 后跟
    • 文字左括号 [(] 后跟
    • 捕获组中的数字(\\d+) 后跟
    • 一个可选的右括号[)]?

    然后用左括号替换它,匹配捕获组\\1 和右括号。

    没有使用任何包。

    pat <- ".*[(](\\d+)[)]?"
    transform(test, Age = sub(pat, "(\\1)", Age))
    

    如果您希望将年龄作为数字字段,则:

    transform(test, Age = as.numeric(sub(pat, "\\1", Age)))
    

    2) substring/sub 另一种可能性是从第 13 个字符开始,它给出从左括号到字符串末尾的所有内容,如果缺失,则插入 a )。 )?$ 匹配字符串末尾的右括号,如果没有,则仅匹配字符串的末尾。用右括号代替。同样,没有使用任何包。

    transform(test, Age = sub(")?$", ")", substring(Age, 13))
    

    如果我们想要一个数字 Age 的一种变体,那就是从第 14 个字符中取出所有内容并删除最后的 )(如果存在)。

    transform(test, Age = as.numeric(sub(")", "", substring(Age, 14))))
    

    3) read.table 使用read.table 读取带有sep = "("comment.char = ")"Age 字段,然后选择读取的第二列。这将给出数字年龄,我们可以使用sprintf 用括号括起来。如果Age 是字符(而不是因子),那么as.character(Age) 可以选择写为Age

    同样,没有使用任何包。这个不使用正则表达式。

    transform(test, Age = 
      sprintf("(%s)", read.table(text = as.character(Age), sep = "(", comment.char = ")")$V2)
    

    注意:可重现形式的输入是:

    test <- data.frame(Age = c("Sep 10, 1990(27)", "Mar 26, 1987(30", "Feb 24, 1997(20)"))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-14
      • 1970-01-01
      • 2021-06-20
      • 2020-08-15
      • 1970-01-01
      • 1970-01-01
      • 2021-12-25
      相关资源
      最近更新 更多