Greg Greg - 5 months ago 46
R Question

How to Reverse a string in 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.

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"


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

paste(test_rev, collapse='')

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 tells it to operate within a vector instead.