Reputation: 497
Given a
, I have to return b
:
a <- "[1, 2, 3]" # class: character
b <- c(1, 2, 3) # class: numeric
I have tried strsplit()
and paste()
functions but both are not working well. Can I get some help?
Upvotes: 2
Views: 544
Reputation: 263301
I'm guessing that this is from a JSON source, so there are packages for that:
library(jsonlite) # obviously needs to be installed first
fromJSON(a)
#[1] 1 2 3
JSON files always are read into R functions from type character but the converted to R objects with typing conventions like that of read.table.
Upvotes: 3
Reputation: 26218
stringr
(tidyverse
) way of doing it
library(stringr)
a <- "[1, 2, 3]"
str_split(a, ',') %>% unlist %>%
str_replace('\\D*(\\d*)\\D*', '\\1') %>%
as.numeric()
#> [1] 1 2 3
Created on 2021-06-27 by the reprex package (v2.0.0)
Upvotes: 0
Reputation: 520898
I prefer to do a regex find all to extract all digits. Then, cast the character vector output to numeric:
a <- "[1, 2, 3]"
b <- as.numeric(regmatches(a, gregexpr("[0-9]+", a))[[1]])
b
[1] 1 2 3
Upvotes: 1
Reputation: 388807
Clean the string with gsub
, split it on comma and convert it to numeric.
b <- as.numeric(unlist(strsplit(gsub('\\[|\\]', '', a), ',\\s+')))
b
#[1] 1 2 3
Upvotes: 1