使用units包我可以创建一个带有物理单位的向量,例如:
library(units)
a = 1:10
units(a) <- with(ud_units, m/s)
a
## Units: m/s
## [1] 1 2 3 4 5 6 7 8 9 10
Run Code Online (Sandbox Code Playgroud)
但是如何在没有单位的情况下回到普通的R矢量?
unclass(a) 完成大部分工作,但在向量中留下了一堆属性:
unclass(a)
## [1] 1 2 3 4 5 6 7 8 9 10
## attr(,"units")
## $numerator
## [1] "m"
##
## $denominator
## [1] "s"
##
## attr(,"class")
## [1] "symbolic_units"
Run Code Online (Sandbox Code Playgroud)
但我觉得应该有一个更简单的方法.分配为unitless没有帮助,它创建一个具有"无单位"单位的向量.
小插图中没有任何东西......
您可以使用as.vector
或者更一般地说:
clean_units <- function(x){
attr(x,"units") <- NULL
class(x) <- setdiff(class(x),"units")
x
}
a <- clean_units(a)
# [1] 1 2 3 4 5 6 7 8 9 10
str(a)
# int [1:10] 1 2 3 4 5 6 7 8 9 10
Run Code Online (Sandbox Code Playgroud)