Unit conversions: Difference between revisions

From Opasnet
Jump to navigation Jump to search
(code moved to Opasnet (R library))
Line 1: Line 1:
[[Category:R tool]]
[[Category:R tool]]
{{tool|moderator=Jouni|stub=Yes}}
{{tool|moderator=Jouni|stub=Yes}}
:''The code related to this tool is now a part of [[Opasnet (R library)]].
==Question==
==Question==


Line 13: Line 16:
toe|MJ|35000|1 toe = 1000 kgoe = 1000 kg * 35 MJ/kg = 35000 MJ
toe|MJ|35000|1 toe = 1000 kgoe = 1000 kg * 35 MJ/kg = 35000 MJ
</t2b>
</t2b>
<rcode
include="page:Opasnet_(R_library)|name:answer"
>
############# convert.units: a function that converts units from one to another, if possible.
#    value    = a numeric vector with values to be converted
#    fromunit  = a numeric vector with the current units
#    tounit    = a string for the new units to be used. Must be found from the To column from the table in [[Unit conversions]].
#    expo      = exponent for the conversion. If -1 converts the inverse, i.e. backward, or a unit that is in the denominator of a compiled unit.
convert.units <- function(value, fromunit = NULL, tounit = NULL, expo = 1) {
data <- fetch("Op_en5475")
print(data)
out <- merge(fromunit, data, by.y = "From")
print(out)
out <- out[out$To == tounit, ]
print(out)
out <- merge(value, out, all.x = TRUE)
print(out)
out <- out$value * out$Factor^expo
print(out)
return(out)
}
cat("Starting model\n")
a <- data.frame(Unit = "MW", Result = 1)
convert.units(1, "MWh", "MJ")
temp <- setGeneric("convert.units")
temp <- setMethod(
f = "convert.units",
signature = signature(data = "ovariable"),
definition = function(x, tounit = NULL)
{
x@sample[c("Unit", "Result")] <- convert.units(x@sample$Result, x@sample$Unit, tounit)
return(x)
}
)
</rcode>
{{attack|# |The code does not work because the merges and combinations do not match. Values should have some row identifier that makes it possible to link a row in value to the right row in out. Should value and fromunit be two columns in a data.frame?|--[[User:Jouni|Jouni]] 11:29, 25 January 2012 (EET)}}

Revision as of 13:48, 31 May 2012



The code related to this tool is now a part of Opasnet (R library).

Question

How to convert data from one unit to another in R?

Answer

We need conversion factors, which are listed below, and a code that does the actual conversion.

Unit conversions: Difference between revisions(-)
ObsFromToResultDescription
1MWhMJ36001 MWh = 1 MWh * 3600 s/h = 3600 MWs = 3600 MJ
2toeMJ350001 toe = 1000 kgoe = 1000 kg * 35 MJ/kg = 35000 MJ