Home > Net >  How can I get string '1,2,3' not '1:3'
How can I get string '1,2,3' not '1:3'

Time:01-28

There is a string: s <- '[[1,2,3],[2,5,6]]'

I use package jsonlite to:

s <- fromJSON(s) 
s <- split(s, row(s))

Then, I get a matrix like this:

A matrix: 2 × 3 of type int
1 2 3
2 5 6

I hope I can use as.character(s[1]) to make s[1] become '1,2,3'. However I get this '1:3'

as.character(s[1])
'1:3'

What should I do?

CodePudding user response:

A possible solution:

s <- matrix(1:6,2,3, byrow=T)
s

#>      [,1] [,2] [,3]
#> [1,]    1    2    3
#> [2,]    4    5    6

paste(s[1,], collapse=",")

#> [1] "1,2,3"

Without conversion to matrix:

library(stringr)

s <- '[[1,2,3],[2,5,6]]'

str_extract(s, "(?<=^\\[\\[).*(?=\\],)")

#> [1] "1,2,3"

CodePudding user response:

With apply:

s <- '[[1,2,3],[2,5,6]]'
s <- jsonlite::fromJSON(s)
s <- apply(s,1,paste,collapse=',')
s[1]
[1] "1,2,3"
  •  Tags:  
  • Related