r specify the first element in a vector

Viewed 80

I have a vector of hundreds of animals (none of which repeat), and I want "whale" to be first. I don't care about the order of any other element, and I can't specify something like alphabetical order. How would I make something like this:

animals <- c("cat", "dog", "whale", "pig", "zebra", "emu")

Look like this, without having to retype every element:

whale_first <- c("whale", "cat", "dog", "pig", "zebra", "emu")

I tried looking at sort() and str_order(), but I couldn't find a way to specify just the first element. Also, in the final answer, it does not matter the order of the other animals. My example here kept them all in the same order, except for whale, but I'll accept all other animals in any order.

Thank you!

3 Answers

An one-liner is setdiff (assuming no duplicates)

c("whale", setdiff(animals, 'whale'))

If there are duplicates, use vsetdiff

library(vecsets)
c("whale", vsetdiff(animals, 'whale'))

swaping:

first <- animals[1]
i <- grep("whale", animals)
animals[1] <- animals[i]
animals[i] <- first

if you dont care :

i <- grep("whale", animals)
c(animals[i],animals[-i])

of course you could also do:

c("whale", grep("whale", animals, value = TRUE, invert=TRUE))

A base R method that is safe for duplicates is to re-order factors:

animals = factor(animals)
levels(animals) = c('whale', setdiff(levels(animals), 'whale'))
animals = as.character(animals)
Related