Turning a string of numbers into a list of numbers in R

后端 未结 4 524
渐次进展
渐次进展 2021-01-21 05:09

Apologies if this question is too easy, I know how to do it in Python but I currently need it in R.

As part of an SQL query I get a variable with some numbers (the lengt

4条回答
  •  自闭症患者
    2021-01-21 05:32

    We can extract the first list elements and convrert to numeric

    library(stringr)
    as.numeric(str_extract_all(x, "[0-9.]+")[[1]])
    #[1] 0.50 0.25 0.75 0.50
    

    Or with base R using regmatches/regexpr

    as.numeric(regmatches(x, gregexpr("[0-9.]+", x))[[1]])
    #[1] 0.50 0.25 0.75 0.50
    

    Or with scan after removing the curly brackets

    scan(text= gsub("[{}]", "", x), what = numeric(), sep="," , quiet = TRUE)
    

提交回复
热议问题