Iterating over characters of string R

前端 未结 4 880
一整个雨季
一整个雨季 2021-02-19 10:24

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

numberstring <- \"0123456789\"

for (number in numberstring) {
  print(num         


        
4条回答
  •  再見小時候
    2021-02-19 10:53

    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"
    

提交回复
热议问题