OpasnetUtils/Ops

From Testiwiki
Revision as of 09:52, 25 March 2013 by Jouni (talk | contribs) (idea of Getrescol)
Jump to: navigation, search



Description

Arithmetic operations of ovariables: first they are merged by index columns, then the operation is performed for the Result.x and Result.y columns.

If one of the expressions is numeric, it is first transformed to ovariable.

Using other functions

A problem with non-common functions is that the operations are typically done for the ovariable@output$rescol only, where rescol is the column containing the actual result. For Ops and Math, there is a specifically designed function for performing the operations, but it is not feasible to develop specific S4 functions for all possible functions people want to apply to ovariables.

Instead, we could use a generic function which can be used to squeeze the rescol of interest out of the ovariable in a simple way, apply any functions applicable for vectors, and then assign the outcome back into ovariable. This can be done with Getrescol function. Getrescol is developed from a part of Ops function.

- Hide code


library(OpasnetUtils)

### Getrescol returns a vector that contains the result column of the
### output of a given ovariable. The vector contains the original column
### name as the attribute comment.
### e1 is the ovariable to operate with.

Getrescol <- function(e1) { # e1 must be an ovariable or a data.frame.

# Should we allow people to use this for data.frames as well?
#	if(class(e1) == "data.frame") e1 <- new("ovariable", name = character(), output = e1)

	# First check presence of name specific Result-columns
		
	test1 <- "Result" %in% colnames(e1@output)
		
	test3 <- paste(e1@name, "Result", sep = "") %in% colnames(e1@output)
		
	# If found take note
		
	rescol1 <- ifelse(test1, "Result", paste(e1@name, "Result", sep = ""))
		
	if(!(test1 | test3)) stop("No result column found while operating mathematically with ovariables!\n")

	out <- e1@output[[rescol1]]
	comment(out) <- rescol1 # Save the column name for later use
	
	return(out)
}

## "Getrescol<-" is a function that tells what is done if content is assigned into Getrescol(ovariable).
## e1 is the ovariable into which something is assigned.
## value is the thing to assign into the ovariable.

assign("Getrescol<-", function(e1, value) {
	e1@output[[comment(Getrescol(e1))]] <- value
	return(e1)}
)

a <- new("ovariable", 
	name = "a", 
	output = data.frame(A = 1:5, Result = 11:15)
)

Getrescol(a)
Getrescol(a) <- Getrescol(a) * 2
a


Code

https://www.opasnet.org/svn/opasnet_utils/trunk/R/Ops.r

See also