Home > Back-end >  String lengths after splitting
String lengths after splitting

Time:11-23

I have a string I would like to split and access the elements as strings. Here is code:

x <- "b0.5,0.5"
y <- strsplit(x,',')
str(y)
y[[1]][1]
str(y[[1]][1])
length(y[[1]][1])
z <- y[[1]][1]
length(z)
substr(z,1,1)
substr(z,1,2)
substr(z,1,3)
substr(z,1,4)

The length of z is 1, but I can access at least 4 substrings of length 1. Can someone explain this to me? Thanks!

CodePudding user response:

Well strsplit() returns a list, so if you want a character vector of components as a result, then unlist the return value:

x <- "b0.5,0.5"
y <- unlist(strsplit(x, ","))
y

[1] "b0.5" "0.5" 

CodePudding user response:

Depending on how many entries you have my suggestion would be to use sapply:

x <- "b0.5,0.5"
y <- strsplit(x,',')


sapply(y, \(z) z)

     [,1]  
[1,] "b0.5"
[2,] "0.5" 
  • Related