简体   繁体   English

从 R 向量中删除单位

[英]Removing units from an R vector

Using the units package I can create a vector with physical units, for example:使用units package 我可以创建一个带有物理单位的矢量,例如:

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

but how do I get back to a plain R vector without units?但是我如何回到没有单位的普通 R 向量?

unclass(a) does most of the work, but leaves a bunch of attributes in the vector: 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"

but I feel there should be a simpler way.但我觉得应该有一个更简单的方法。 Assigning as unitless doesn't help, it creates a vector with "unitless" units.分配为unitless没有帮助,它会创建一个带有“无单位”单位的向量。

Nothing in the vi.nette either... vi.nette 中也没有任何内容......

You can use as.vector :) 你可以使用as.vector :)

or to be more general : 或者更一般:

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

Note that nowadays there is the drop_units function making this much easier and more intuitive:请注意,现在有drop_units function 使这更容易和更直观:

library(units)
#> udunits database from /usr/share/xml/udunits/udunits2.xml
a = set_units(1:10,'m/s')
a
#> Units: [m/s]
#>  [1]  1  2  3  4  5  6  7  8  9 10
drop_units(a)
#>  [1]  1  2  3  4  5  6  7  8  9 10

Created on 2021-09-28 by the reprex package (v2.0.1)reprex package (v2.0.1) 创建于 2021-09-28

as.vector should work in this case: as.vector应该在这种情况下工作:


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
str(a)                         
#> Class 'units'  atomic [1:10] 1 2 3 4 5 6 7 8 9 10
#>   ..- attr(*, "units")=List of 2
#>   .. ..$ numerator  : chr "m"
#>   .. ..$ denominator: chr "s"
#>   .. ..- attr(*, "class")= chr "symbolic_units"

b = as.vector(a)               
str(b)                         
#>  int [1:10] 1 2 3 4 5 6 7 8 9 10

I guess as.vector can be made to work with matrices too 我想as.vector也可以用于矩阵

#DATA
set.seed(42)
m = set_units(matrix(rnorm(4), 2), m/s)
m
#Units: m/s
#           [,1]      [,2]
#[1,]  1.3709584 0.3631284
#[2,] -0.5646982 0.6328626

class(m)
#[1] "units"

foo = function(x){
    y = as.vector(x)
    dim(y) = dim(x)
    return(y)
}

foo(m)
#           [,1]      [,2]
#[1,]  1.3709584 0.3631284
#[2,] -0.5646982 0.6328626

class(foo(m))
#[1] "matrix"

foo(a)
# [1]  1  2  3  4  5  6  7  8  9 10

class(foo(a))
#[1] "integer"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM