Stephen Stretton Stephen Stretton - 2 months ago 15
R Question

Change multiple elements in R vector with repeated names

Let's say I have a vector with repeated names:

x <- c(a=1, b=2, a=3, c=4, c=5, b=1, d=1)


I want to lookup and change named elements. If I define

ElementsToChange=c("a","b","c")

ChangeTo <- c(9,8,7)


I want to change all the elements named 'a' to 9 all those named 'b' to 8 etc. if I do:

x[ElementsToChange] <- ChangeTo


This will only change only the first (rather than all) elements.

How do I change all, in a simple and elegant way?

Answer Source

You can do it using a single split* command:

split(x, names(x))[ElementsToChange] <- ChangeTo
#x
#a b a c c b d 
#9 8 9 7 7 8 1 

This first splits the x vector by its names, then subsets all elements that are part of the ElementsToChange vector and replaces those values with the ChangeTo values.

* technically, you're using split<- here, i.e. assignment on the splitted data. The original vector keeps its structure afterwards.