Unit conversions: Difference between revisions
Jump to navigation
Jump to search
(placeholder) |
mNo edit summary |
||
Line 16: | Line 16: | ||
<rcode> | <rcode> | ||
############# Unit.convert: a function that converts units from one to another, if possible. | ############# Unit.convert: a function that converts units from one to another, if possible. | ||
# value = a numeric vector with values to be converted | # value = a numeric vector with values to be converted | ||
# fromunit = a numeric vector with the current units | # 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]]. | # tounit = a string for the new units to be used. Must be found from the To column from the table in [[Unit conversions]]. | ||
unit.convert <- function(value, fromunit, tounit) { | # 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. | ||
unit.convert <- function(value, fromunit, tounit, expo = 1) { | |||
data <- tidy(op_baseGetData("opasnet_base", "Op_enXXXX")) | data <- tidy(op_baseGetData("opasnet_base", "Op_enXXXX")) | ||
out <- merge(fromunit, data, by.y = data$From) | out <- merge(fromunit, data, by.y = data$From) | ||
out <- out[out$To == tounit, ] | out <- out[out$To == tounit, ] | ||
out <- merge(value, out, all.x = TRUE) | |||
out <- out$value * out$Factor^expo | |||
return(out) | return(out) | ||
} | } |
Revision as of 09:32, 25 January 2012
Moderator:Jouni (see all) |
This page is a stub. You may improve it into a full page. |
Upload data
|
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.
Obs | From | To | Factor | Description |
---|---|---|---|---|
1 | MWh | MJ | 3600 | 1 MWh = 1 MWh * 3600 s/h = 3600 MWs = 3600 MJ |
2 | toe | MJ | 35000 | 1 toe = 1000 kgoe = 1000 kg * 35 MJ/kg = 35000 MJ |
⇤--#: . 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? --Jouni 11:29, 25 January 2012 (EET) (type: truth; paradigms: science: attack)