Reputation: 1399
I can't figure out what I'm doing wrong. I'm trying to reorder a string, and the easiest way that I could think of doing so was by removing elements and then putting them back in using paste. But I can't figure out how to remove elements. Here's a string:
x <- "the.cow.goes.moo"
But when I use
x <- strsplit(x, '[.]')
resulting in the list "the" "cow" "goes" "moo". And try to remove the second element using either
x <- x[-2]
or
[x <- x[x != "cow"]
I get the exact same list. But when I declare x as
x <- list("the", "cow", "goes", "moo")
then
x <- x[-2]
works!
What's different? What am I doing wrong? Also, is there an easier way to reorder a string?
EDIT: I just realized that what I need is "moo.goes.the.cow", but I need to repeat this same change for a number of other strings. So I need to reorder the elements, and can't actually delete them. How can I do that?
Upvotes: 2
Views: 4011
Reputation: 44648
strsplit
returns a list
object. So each element of the vector x
will now be broken out into individuals pieces in a list
. Lists can be painful to subset in this fashion but it's good to get your head around it early.
In your example, it would be:
x[[1]][-2]
For your update, you can reorder like so:
x[[1]][c(2,1,3,4)] # or whatever order you want.
x[[1]][sample(1:x[[1]],length(x[[1]]))] # randomly even
Upvotes: 2