2

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.

zx8754
  • 52,746
  • 12
  • 114
  • 209
Johnny
  • 161
  • 3
  • 14

2 Answers2

2

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
zx8754
  • 52,746
  • 12
  • 114
  • 209
0

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
RLave
  • 8,144
  • 3
  • 21
  • 37