Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating over characters of string R

Could somebody explain me why this does not print all the numbers separately in R.

numberstring <- "0123456789"

for (number in numberstring) {
  print(number)
}

Aren't strings just arrays of chars? Whats the way to do it in R?

like image 258
Lukasz Avatar asked Nov 03 '14 19:11

Lukasz


3 Answers

In R "0123456789" is a character vector of length 1.

If you want to iterate over the characters, you have to split the string into a vector of single characters using strsplit.

numberstring <- "0123456789"

numberstring_split <- strsplit(numberstring, "")[[1]]

for (number in numberstring_split) {
  print(number)
}
# [1] "0"
# [1] "1"
# [1] "2"
# [1] "3"
# [1] "4"
# [1] "5"
# [1] "6"
# [1] "7"
# [1] "8"
# [1] "9"
like image 66
Sven Hohenstein Avatar answered Oct 17 '22 22:10

Sven Hohenstein


Just for fun, here are a few other ways to split a string at each character.

x <- "0123456789"
substring(x, 1:nchar(x), 1:nchar(x))
# [1] "0" "1" "2" "3" "4" "5" "6" "7" "8" "9"
regmatches(x, gregexpr(".", x))[[1]]
# [1] "0" "1" "2" "3" "4" "5" "6" "7" "8" "9" 
scan(text = gsub("(.)", "\\1 ", x), what = character())
# [1] "0" "1" "2" "3" "4" "5" "6" "7" "8" "9"
like image 42
Rich Scriven Avatar answered Oct 17 '22 21:10

Rich Scriven


Possible with tidyverse::str_split

numberstring <- "0123456789"
str_split(numberstring,boundary("character"))

1. '0''1''2''3''4''5''6''7''8''9'
like image 2
mini_lils Avatar answered Oct 17 '22 22:10

mini_lils