【问题标题】:converting pasted numbers to vector of numbers in r将粘贴的数字转换为 r 中的数字向量
【发布时间】:2015-02-01 08:53:56
【问题描述】:

我想将以下字符串转换为单独的值,包括减号

t <- "111111111-1-1-1-1-1-1-1-11111-1-1-1-1-1111111-1-1-1-1-1-1-1-111111-1-1-1-111111-1-1-1-1-1-1-1-111111-1-1-1-1111111-1-1-1-1-1-1-1-1111-1-1-1-111111111"

(1,1,1,1,1,1,1,1,1,-1,-1,-1,-1,-1,-1,-1, etc)

我们非常感谢任何建议。

【问题讨论】:

    标签: r substring


    【解决方案1】:

    你可以使用strsplit:

    as.integer(strsplit(t, "(?<=\\d)", perl = TRUE)[[1]])
    

    结果:

     [1]  1  1  1  1  1  1  1  1  1 -1 -1 -1 -1 -1 -1 -1 -1  1  1  1  1 -1 -1 -1 -1
     [26] -1  1  1  1  1  1  1 -1 -1 -1 -1 -1 -1 -1 -1  1  1  1  1  1 -1 -1 -1 -1  1
     [51]  1  1  1  1 -1 -1 -1 -1 -1 -1 -1 -1  1  1  1  1  1 -1 -1 -1 -1  1  1  1  1
     [76]  1  1 -1 -1 -1 -1 -1 -1 -1 -1  1  1  1 -1 -1 -1 -1  1  1  1  1  1  1  1  1
    

    【讨论】:

      【解决方案2】:

      另一种选择是使用gregexprregmatches

      as.integer(regmatches(t,gregexpr("\\d|-\\d",t))[[1]])
      

      【讨论】:

        【解决方案3】:

        使用stringrstr_extract_all函数

        as.integer(str_extract_all(t, '-?\\d')[[1]])
        

        结果

        [1]  1  1  1  1  1  1  1  1  1 -1 -1 -1 -1 -1 -1 -1 -1  1  1  1  1 -1 -1 -1 -1 -1  1  1  1  1  1  1 -1 -1 -1 -1 -1 -1 -1 -1  1
        [42]  1  1  1  1 -1 -1 -1 -1  1  1  1  1  1 -1 -1 -1 -1 -1 -1 -1 -1  1  1  1  1  1 -1 -1 -1 -1  1  1  1  1  1  1 -1 -1 -1 -1 -1
        [83] -1 -1 -1  1  1  1 -1 -1 -1 -1  1  1  1  1  1  1  1  1
        

        检查

        > nchar(t)
        [1] 149
        > nchar(str_replace_all(t, '\\d', ''))
        [1] 49
        > length(as.integer(str_extract_all(t, '-?\\d')[[1]]))
        [1] 100
        

        【讨论】:

        • stringi 类似,如library(stringi) ; as.integer(stri_extract_all(t, regex = '-?\\d')[[1]])
        • Wilson、mrip 和 David:非常感谢您的快速回答。我肯定问对了人!
        猜你喜欢
        • 1970-01-01
        • 2012-12-12
        • 2014-10-03
        • 1970-01-01
        • 2021-07-24
        • 1970-01-01
        • 1970-01-01
        • 2016-05-03
        • 2023-01-18
        相关资源
        最近更新 更多