Search code examples
rloopsvectorcharacterstrsplit

How do I create a vector of characters from a character object?


I need to convert a character type of object like:

"1234"
"1123"
"0654"
"0001"

to a vector like:

1,2,3,4,1,1,2,3,0,6,5,4,0,0,0,1

I was able to use strsplit to separate each of the group of for numbers into individual characters, but I can't add them to a single object.

The for loop I used:

number_0
number_0_vect <- vector("list",1024)

for (number in number_0){
  line_vects <- strsplit(number, "")[[1]]
  for (line_vect in line_vects){
    number_0_vect[line_vect] <- line_vect
  }
}

Where number 0 is a character type with a length of 32 (each of the strings has 32 characters, so the final vector will have 1024 items). I don't get any errors, but when I print the object number_0_vect it gives me "NULL" values.

I am quite new to R and I it's the second time I asked a question in Stack Overflow, I hope I did it well.


Solution

  • If somehow you hate to use unlist() you can first paste each element in x then use stringr::str_split:

    x <- c("1234", "1123", "0654", "0001")
    as.numeric(stringr::str_split(paste(x, collapse = ""), "")[[1]])
    #[1] 1 2 3 4 1 1 2 3 0 6 5 4 0 0 0 1