I've been baffled by this a few times already, so here's a made-up question for others who might stumble upon the same problem.
Consider this grid unit vector,
a = unit(1:3, c("cm", "in", "npc"))
I want to replace some elements with new values. The natural approach would be,
a[1] = unit(2,"pt")
a
# [1] 2cm 2in 3npc
Something went wrong: only the numeric value was changed, not the unit. Why? What to do?
Edit: As pointed out in one answer below, such units are just numeric vectors with attributes. However, their offsprings unit.arithmetic
and unit.list
should also be considered solution to be fully general (e.g to use in adjusting panel sizes of ggplot objects). Consider this unit vector,
(b = a + unit(1, "npc"))
# [1] 1cm+1npc 2in+1npc 3npc+1npc
# [1] "unit.arithmetic" "unit"
Now replacing a specific element is more tricky, since they're not atomic anymore.