brygid
brygid

Reputation: 85

replace value from smaller vector to bigger vector

I have a vector with a random set of 100 values, 1:20, "testing01", and a set of different 20 values "testing02".

now i want to change the values in "testing01" into "testing02", by rule presented in "ff" so all "1" in testing01 turns into "2" all "2" in testing01 turns into "16" (according to my sample()in "testing02")

i will use the new vector to recreate a matrix "testing04" to update "testing03"

testing01 <- as.vector(matrix(sample(1:20), 10,10))
testing02 <- c(sample(20,20))
testing03 <-matrix(testing01,10,10)
ff<- rbind(seq(unique(testing01)),testing02)

how can I replace the values?


It happened that the problem i wanted to solve was a bit different than the first example i gave. please allow me to update the example (i leave the old one in case it would be useful for someone else :))

t1 <-c(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,
22,23,24,25,26,27,28,29,30,31,32,33,34,36,37,40,41,42,44,45,46,
47,48,50,51,57,61,62)

t2 <-c(0,1,3,2,5,4,7,6,9,8,11,11,12,13,14,15,16,16,18,18,20,21,23,22,
24,24,26,26,28,28,31,31,32,32,34,36,37,41,40,42,44,45,46,47,49,51,
51,57,60,63)
newrule <-rbind(t1,t2)
set.seed(24)
t3 <- c(matrix(sample(t1),10,10))

The goal is to update "t3" by changing "t1" values using "t2" values, creating a new vector "t4" (so all 2 turns to 3,10 turns to 11, 11 remains 11, 16 remains 16..and so on)

Upvotes: 1

Views: 143

Answers (1)

akrun
akrun

Reputation: 887951

Try

unname(setNames(ff[2,], ff[1,])[testing01])

Update

May be this helps

v1 <- unname(setNames(newrule[1,], newrule[2,])[as.character(t3)])
ifelse(is.na(v1), t3, v1)

Or

colSums(rbind(v1,is.na(v1)*t3), na.rm=TRUE)

Upvotes: 1

Related Questions