Tou Mou
Tou Mou

Reputation: 1274

How to replace vector elements based on their positions at a list?

Good morning !

Suppose we have the following :

set.seed(1)
x <- sample(c(1,2,3,4,5,6,7,8,9),size=15,replace=TRUE)
x
library(dplyr)
x=case_when(x %in% 1:3 ~ 1, x %in% 6:8 ~ 2, x %in% c(4, 5, 9) ~ 3)
print("after")
x

Output :

    3 4 6 9 2 9 9 6 6 1 2 2 7 4 7

[1] "after"

    1 3 2 3 1 3 3 2 2 1 1 1 2 3 2

This code replace a set of values like {6,7,8} in the vector x with one specific value like 2.

What i'm wanting to do is to store the vectors 1:3 , 6:8 , c(4, 5, 9) in a list list_1 to obtain the same output. I'm searching a solution that easily works if the length of the list list_1 as well as the replacement rules changes. Note that the number of replacement rules is usually equal to the list list_1 length.

I hope my question is clear! Thank you in advance for help!

Upvotes: 1

Views: 312

Answers (1)

ThomasIsCoding
ThomasIsCoding

Reputation: 102700

Maybe you can try the code below

with(stack(setNames(list_1,c(1,2,3))),as.numeric(ind[match(x,values)]))

Example

> x
 [1] 9 4 7 1 2 7 2 3 1 5 5 6 7 9 5

> with(stack(setNames(list_1,c(1,2,3))),as.numeric(ind[match(x,values)]))
 [1] 3 3 2 1 1 2 1 1 1 3 3 2 2 3 3

Another option is using matrix multiplication

> c(t(c(1,2,3)) %*% do.call(rbind,Map(function(v) x%in% v,list_1)))     
 [1] 3 3 2 1 1 2 1 1 1 3 3 2 2 3 3

Upvotes: 2

Related Questions