【问题标题】:How to extract the substring of a string by "not" select?如何通过“非”选择提取字符串的子字符串?
【发布时间】:2021-08-07 20:29:15
【问题描述】:

我有一个奇怪的日期列写成

2003 年 1 月 1 日的 1012003, 2003 年 8 月 13 日的 8132003 2003 年 6 月 8 日的 6082003 12172003 为 2003 年 12 月 17 日 使用

stri_sub(df$date,-4) 

我得到年份或最后 4 位数字

使用

stri_sub(df$date,-6,-5)

我知道日期了。我如何获得月份?

我想做一些事情,根据选择最右边的 6 个来选择剩余的内容。

我认为这样的事情可能会奏效

  stri_sub(!df$date,-6)

我想留下 1、8、6 和 12。

【问题讨论】:

  • 只提取第一个 / 之前的数字。或者,提取前两个符号,如果第二个是 /,则将其放在“”。
  • 没有行。它只是这样写“1012003”而不是“10/12/200”
  • 是的。对不起,我看错了你的帖子。

标签: r string substring


【解决方案1】:

这是一种方法:

> x <- c('1012003', '8132003', '6082003', '12172003')
> substr(x, 1, nchar(x) - 6)
[1] "1"  "8"  "6"  "12"

【讨论】:

    【解决方案2】:

    你可以添加一个前导零,转换为真实日期,然后对它们做任何你想做的事情......

    v <- c(1012003, 8132003, 6082003 , 12172003)
    
    # Add leading zero if needed
    new.v <- sprintf("%08d", v)
    #[1] "01012003" "08132003" "06082003" "12172003"
    
    # Convert to date
    v.dates <- as.Date(new.v, format = "%m%d%Y")
    #[1] "2003-01-01" "2003-08-13" "2003-06-08" "2003-12-17"
    
    # extract month-numbers
    lubridate::month(v.dates)
    #[1]  1  8  6 12
    

    【讨论】:

      【解决方案3】:

      我们可以稍微扩展substr()

      substr2 <- Vectorize(function(x, start, stop) {
        stopifnot(sign(start) + sign(stop) != 0)
        rv <- function(i) Reduce(paste0, rev(el(strsplit(i, ''))))
        if (start < 0) {
          rv(substr(rv(x), -start, -stop))
        } else {
          substr(x, start, stop)
        }
      }, USE.NAMES=FALSE)
      

      用法

      substr2(z, -1, -4)  ## years
      # [1] "2003" "2003" "2003" "2003"
      
      substr2(z, -5, -6)  ## days
      # [1] "01" "13" "08" "17"
      
      substr2(z, -7, -8)  ## months
      # [1] "1"  "8"  "6"  "12"
      

      数据:

      z <- c('1012003', '8132003', '6082003', '12172003')
      

      【讨论】:

        猜你喜欢
        • 2022-11-15
        • 2018-07-13
        • 1970-01-01
        • 1970-01-01
        • 2021-12-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-17
        相关资源
        最近更新 更多