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

查看:91
本文介绍了遍历字符串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.

如果要遍历字符,则必须使用以下命令将字符串拆分为单个字符的
a向量 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天全站免登陆