19

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?

Wez Sie Tato
  • 1,186
  • 12
  • 33
Lukasz
  • 2,257
  • 3
  • 26
  • 44

5 Answers5

34

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"
Sven Hohenstein
  • 80,497
  • 17
  • 145
  • 168
7

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"
Rich Scriven
  • 97,041
  • 11
  • 181
  • 245
2

Possible with tidyverse::str_split

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

1. '0''1''2''3''4''5''6''7''8''9'
mini_lils
  • 21
  • 1
1

Here's a naive approach for iterating a string using a for loop and substring. This isn't any better than existing answers for the common case, but it might be useful if you want to break out of the loop early instead of always traversing the entire string once up front, as str_split/scan/substring(x, 1:nchar(x), 1:nchar(x))/regmatches requires.

s <- "0123456789"

if (s != "") {
  for (i in 1:nchar(s)) {
    print(substring(s, i, i))
  }
}

The if is needed to avoid looping backwards from 1 to 0, inclusive of both ends.

ggorlen
  • 44,755
  • 7
  • 76
  • 106
-4

Your question is not 100% clear as to the desired outcome (print each character individually from a string, or store each number in a way that the given print loop will result in each number being produced on its own line). To store numberstring such that it prints using the loop you included:

numberstring<-c(0,1,2,3,4,5,6,7,8,9)
for(number in numberstring){print(number);}

[1] 0
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9
> 
David Arenburg
  • 91,361
  • 17
  • 137
  • 196
Greg Syme
  • 392
  • 3
  • 8