Replacing elements in a vector mesh element

I’ve been confused several times, so here is the 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. A natural approach would be

 a[1] = unit(2,"pt") a # [1] 2cm 2in 3npc 

Something went wrong: only the numerical value changed, not the unit. What for? What to do?

Edit: As indicated in one of the answers below, such units are simply numeric vectors with attributes. However, their offspring unit.arithmetic and unit.list should also be considered as a completely general solution (for example, use ggplot when setting sizes of object panels). Consider this unit vector,

 (b = a + unit(1, "npc")) # [1] 1cm+1npc 2in+1npc 3npc+1npc # [1] "unit.arithmetic" "unit" 

Replacing a particular element is now more complex since they are no longer atomic.

+5
source share
3 answers
+3
source

After discussing with Paul Murrell (and, funny, reinventing what I understood earlier ), the problem is the lack of a [<- for grid nodes. A long-term solution would be to implement these methods, but this is not trivial, since the grid devices come in with siblings such as unit.arithmetic and unit.list, and their interaction can be complicated.

A lighter, user-oriented solution is to convert such unit vectors to unit.list objects that inherit an access method more similar to regular R-lists. This promotion of the unit.list object can be done using the unexcited grid:::unit.list() function.

 a = unit(1:3, c("cm", "in", "npc")) b = grid:::unit.list(a) is.list(b) # check that indeed this is a list object, thanks @Josh O'Brien # [1] TRUE # so now we can use standard list methods b[[1]] = unit(2,"pt") b #[1] 2pt 2in 3npc 
+3
source

It looks like a is just an atomic vector with attributes attached to it. So, when you use a[1] = unit(2,"pt") , the new unit function creates another atomic vector with a length of one, which replaces the value of a[1] . Attributes remain intact.

So it looks like this works:

 a[1] <- 2 attr(a, 'unit')[1] <- 'pt' > a [1] 2pt 2in 3npc 
+2
source

Source: https://habr.com/ru/post/1237206/


All Articles