遍历字符串 R 的字符 [英] Iterating over characters of string R

查看:37
本文介绍了遍历字符串 R 的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以解释一下为什么这不会在 R 中单独打印所有数字.

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

numberstring <- "0123456789"

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

字符串不只是字符数组吗?在 R 中怎么做?

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

推荐答案

在 R 中 "0123456789" 是长度为 1 的字符向量.

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

如果要遍历字符,则必须将字符串拆分为使用 strsplit 的单个字符向量.

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"

这篇关于遍历字符串 R 的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆