如何反转R中的字符串 [英] How to Reverse a string in R

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

问题描述

我正在尝试自学 R,在做一些示例问题时,我遇到了反转字符串的需要.

I'm trying to teach myself R and in doing some sample problems I came across the need to reverse a string.

这是我迄今为止尝试过的,但粘贴操作似乎没有任何效果.

Here's what I've tried so far but the paste operation doesn't seem to have any effect.

一定有什么我不了解列表的地方吗?(我也不明白为什么我在 strsplit 之后需要 [[1]].)

There must be something I'm not understanding about lists? (I also don't understand why I need the [[1]] after strsplit.)

> test <- strsplit("greg", NULL)[[1]]
> test
[1] "g" "r" "e" "g"
> test_rev <- rev(test)
> test_rev
[1] "g" "e" "r" "g"
> paste(test_rev)
[1] "g" "e" "r" "g"

推荐答案

正如@mplourde 指出的那样,您需要 collapse 参数:

As @mplourde points out, you want the collapse argument:

paste(test_rev, collapse='')

R 中的大多数命令都是向量化的,但是命令处理向量的方式取决于命令.paste 将操作多个向量,结合每个向量的 ith 元素:

Most commands in R are vectorized, but how exactly the command handles vectors depends on the command. paste will operate over multiple vectors, combining the ith element of each:

> paste(letters[1:5],letters[1:5])
[1] "a a" "b b" "c c" "d d" "e e"

collapse 告诉它改为在向量内操作.

collapse tells it to operate within a vector instead.

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

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