Would it be stupid to recode `dim` to return `length` if `dim(x)==NULL`? [duplicate]

こ雲淡風輕ζ 提交于 2019-12-13 19:17:22

问题


As pointed out in this question and copious official & unofficial R documentation,

x <- complex(15)
dim(x) == NULL

For me it's annoying to have to write a separate method (or if clause) for atomic vectors rather than being able to use dim(x)[1]. Would it be stupid to recode dim (a primitive) so it automatically returns length if dim(x)==NULL?

To be a bit more concrete: Are popular packages going to break if I recode dim in let's say my .Rprofile? Is this stupid for another reason I'm not seeing?


回答1:


It's unclear what you're trying to do, but the NROW and NCOL functions are ways to retrieve extents in a dimension-agnostic way. They treat vectors as column vectors, so NROW(X) is the same as length(x) and NCOL(x) is 1 when x is a vector.

> x <- numeric(10) # or complex, character, logical, etc
> nrow(x)
NULL
> NROW(x)
[1] 10
> NCOL(x)
[1] 1

> m <- matrix(1:10, nrow=5)
> nrow(m)
[1] 5
> NROW(m)
[1] 5
> NCOL(m)
[1] 2


来源:https://stackoverflow.com/questions/25697358/would-it-be-stupid-to-recode-dim-to-return-length-if-dimx-null

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