【问题标题】:Extract digits with decimal from a vector R从向量 R 中提取带小数的数字
【发布时间】:2022-11-03 23:46:57
【问题描述】:

我有以下向量:

c("c(`Kruskal-Wallis chi-squared` = 201.760850624131)", "c(df = 17)", 
"1.26686891197831e-33", "Kruskal-Wallis rank sum test", "delta_Z by criteria"
)

我想要这个输出:

c("201.760850624131", "17", "1.26686891197831e-33")

谢谢你的帮助

【问题讨论】:

    标签: r string extract stringr


    【解决方案1】:

    我们可以在这里尝试使用str_extract 来获取正则表达式选项:

    x <- c("c(`Kruskal-Wallis chi-squared` = 201.760850624131)",
           "c(df = 17)", 
           "1.26686891197831e-33",
           "Kruskal-Wallis rank sum test",
           "delta_Z by criteria"
    )
    output <- as.numeric(na.omit(str_extract(x, "\d+(?:\.\d+)?(?:e[+-]\d+)?")))
    output
    
    [1] 2.017609e+02 1.700000e+01 1.266869e-33
    

    正则表达式的解释:

    • \d+ 匹配一个整数分量
    • (?:\.\d+)? 可选小数部分
    • (?:e[+-]\d+)? 可选指数(正或负)

    【讨论】:

      【解决方案2】:

      我们可以使用str_extract 与匹配一个或多个数字([0-9]+)的正则表达式,后跟一个.,然后是一个或多个数字,e 后跟-+ 和任何数字

      library(stringr)
      as.numeric(na.omit(str_extract(v1, "[0-9]+(\.[0-9]+e[-+]\d+)?")))
      

      -输出

      [1] 2.010000e+02 1.700000e+01 1.266869e-33
      

      【讨论】:

      • 我认为1.26686891197831e-33 在强制为数字时应该为 0
      • 它没有正确考虑最后一个值,它具有“e-31”(“1.26686891197831e-33”)
      猜你喜欢
      • 1970-01-01
      • 2022-10-15
      • 1970-01-01
      • 2015-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-15
      • 2020-08-07
      相关资源
      最近更新 更多