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...
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
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With