J.Sabree
J.Sabree

Reputation: 2526

r specify the first element in a vector

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!

Upvotes: 2

Views: 384

Answers (3)

dww
dww

Reputation: 31452

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)

Upvotes: 0

Onyambu
Onyambu

Reputation: 79208

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))

Upvotes: 1

akrun
akrun

Reputation: 886948

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'))

Upvotes: 2

Related Questions