Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing units from an R vector

Tags:

r

Using the units package I can create a vector with physical units, for example:

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?

unclass(a) does most of the work, but leaves a bunch of attributes in the vector:

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.

Nothing in the vignette either...

like image 660
Spacedman Avatar asked Oct 25 '17 14:10

Spacedman


3 Answers

You can use 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
like image 153
Moody_Mudskipper Avatar answered Nov 08 '22 11:11

Moody_Mudskipper


as.vector should work in this case:


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
like image 33
Jot eN Avatar answered Nov 08 '22 10:11

Jot eN


Note that nowadays there is the drop_units function making this much easier and more intuitive:

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)

like image 22
Bart Avatar answered Nov 08 '22 12:11

Bart