首页 > 解决方案 > 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.

标签: rloopsvectorcharacterstrsplit

解决方案


Using strsplit:

x <- c("1234", "1123", "0654", "0001")
as.numeric(unlist(strsplit(x, "")))
# [1] 1 2 3 4 1 1 2 3 0 6 5 4 0 0 0 1

推荐阅读