【问题标题】:How to change character to numeric vector in R如何在R中将字符更改为数字向量
【发布时间】:2021-09-09 20:13:12
【问题描述】:

鉴于a,我必须返回b

a <- "[1, 2, 3]"   # class: character
b <- c(1, 2, 3)    # class: numeric

我尝试过strsplit()paste() 功能,但都不能正常工作。我能得到一些帮助吗?

【问题讨论】:

    标签: r string vector character numeric


    【解决方案1】:

    我猜这是来自 JSON 源,所以有相应的包:

     library(jsonlite) # obviously needs to be installed first
    
    fromJSON(a)
    #[1] 1 2 3
    

    JSON 文件总是从字符类型读入 R 函数,但转换为 R 对象,具有类似于 read.table 的类型约定。

    【讨论】:

    • 这可能是最好的答案+1。
    【解决方案2】:

    stringr (tidyverse) 方法

    library(stringr)
    a <- "[1, 2, 3]"
    
    str_split(a, ',') %>% unlist %>%
      str_replace('\\D*(\\d*)\\D*', '\\1') %>%
      as.numeric()
    #> [1] 1 2 3
    

    reprex package (v2.0.0) 于 2021-06-27 创建

    【讨论】:

      【解决方案3】:

      我更喜欢使用正则表达式 find all 来提取所有数字。然后,将字符向量输出转换为数字:

      a <- "[1, 2, 3]"
      b <- as.numeric(regmatches(a, gregexpr("[0-9]+", a))[[1]])
      b
      
      [1] 1 2 3
      

      【讨论】:

        【解决方案4】:

        gsub 清除字符串,用逗号分割并转换为数字。

        b <- as.numeric(unlist(strsplit(gsub('\\[|\\]', '', a), ',\\s+')))
        b
        #[1] 1 2 3 
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-07-24
          • 2016-05-03
          • 1970-01-01
          • 1970-01-01
          • 2014-04-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多