element replacement in grid unit vector

天涯浪子 提交于 2019-12-05 08:26:33
baptiste

Following a discussion with Paul Murrell (and, amusingly, re-inventing what I'd figured out before), the problem lies in the absence of a [<- method for grid units. The long-term fix would be to implement those methods, but it's not trivial since grid units come with siblings such as unit.arithmetic and unit.list, and their interaction can become hard to comprehend.

The easier, user-oriented fix, is to convert such unit vectors to unit.list objects, which will inherit an accessor method more like regular R lists. This promotion to unit.list object can be done with the unexported function grid:::unit.list().

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

Looks like a is just an atomic vector with some attributes attached to it. So, when you use a[1] = unit(2,"pt") , the new unit function creates another atomic vector of length one which replaces the value of a[1]. The attributes stay untouched.

So, something like this seems to be working:

a[1] <- 2
attr(a, 'unit')[1] <- 'pt'

> a
[1] 2pt  2in  3npc
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!