【问题标题】:Efficient extraction of several numbers from a character string in R [duplicate]从R中的字符串中有效提取多个数字[重复]
【发布时间】:2023-03-16 23:38:01
【问题描述】:

假设我有字符串

x <-  "   1.1325  -0.9022  -0.1832  -0.5479   0.1236  -0.6556  -1.0599  -0.8881  -0.2136"

我想提取浮点数并以这个向量作为输出:

c(1.1325, -0.9022, -0.1832, -0.5479, 0.1236, -0.6556, -1.0599, -0.8881, -0.2136)

我设法实现的是:

na.omit(as.numeric(strsplit(samp, split = "  ")[[1]]))

我的问题:有没有更有效的方法?

【问题讨论】:

    标签: regex r string parsing


    【解决方案1】:

    我们可以使用scan

    scan(text=x, what=numeric(), quiet=TRUE)
    #[1]  1.1325 -0.9022 -0.1832 -0.5479  0.1236 -0.6556 -1.0599 -0.8881 -0.2136
    

    【讨论】:

      猜你喜欢
      • 2017-02-17
      • 2017-12-30
      • 2018-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-02
      相关资源
      最近更新 更多