Removing Units from an R-Vector

Using the package units, 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 can I return to a simple R-vector without units?

unclass(a) It does most of the work, but leaves a lot 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 believe that there should be an easier way. Assignment unitlessdoes not help, it creates a vector with units "without unit".

Nothing in the vignette either ...

+6
source share
3 answers

You can use as.vector:)

or 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
+2
source

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
+1
source

, 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"
0

All Articles