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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With