Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change multiple elements in R vector with repeated names

Tags:

r

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?

like image 355
Stephen Stretton Avatar asked Aug 22 '17 14:08

Stephen Stretton


People also ask

How do you make a repeated value vector in R?

There are two methods to create a vector with repeated values in R but both of them have different approaches, first one is by repeating each element of the vector and the second repeats the elements by a specified number of times. Both of these methods use rep function to create the vectors.

Which of the following functions is used to create a vector with repeated values?

The vectors are created using the rep function in each of these approaches. For example, rep(1:5, times=5) gives a vector with the sequence 1 to 5 repeated 5 times.

How do I select multiple objects in R?

To select multiple objects in a table view: Press Ctrl-Click to select the row for each object you want to select. To de-select an object in a table view: Re-select the row for each object you want to de-select.


1 Answers

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.

like image 164
talat Avatar answered Sep 19 '22 20:09

talat