dimanche 26 septembre 2021

An if statement returns a different variable on each branch, how can I sub-assign to that variable using only one <- operator?

Consider

a <- b <- 1:3
if(sample(2, 1) == 1) a[2] <- 5 else b[2] <- 5

This is repetitive. I would not like to have to write <- 5 twice. It would be ideal to use

a <- b <- 1:3
assign(if(sample(2, 1) == 1) "a[2]" else "b[2]", 5)

but assign is no good for sub-assignment. What idiomatic alternatives exist?

Aucun commentaire:

Enregistrer un commentaire