vendredi 9 janvier 2015

Generating logic vector in a new data frame column based on two sets of target values

I have a data frame in the form of:



exampleCurrent <- data.frame(value = c(5, 4.5, 3, 2.9, 1.5),
off = as.logical(c("F", "F", "T", "T", "F")),
hiOnTarget = c(5.5, 4, 5, 4.7, 4),
loOnTarget =c(4, 3, 3, 4, 3),
hiOffTarget = c(2, 3, 4, 2, 3),
lowOffTarget = c(1, 2, 1, 1.2, 2))


The context of the data is a measured value, and a logical statement as to if it is a workday or an 'off' day (i.e. a weekend or holiday).


The Target values are calculated variables that identify if the measured value should be considered extreme (in other words, an outlier). A value between these two targets is considered normal, a 'value' which is above the hiTarget or below the loTarget is considered extreme.


If off is False (i.e. 'On'), the value is assessed to see if it is between hiOnTargetand loOnTarget. If off is True, the value needs to be measured against the hiOffTarget and loOffTarget


I would like to get to the following:



exampleWanted <- data.frame(value = c(5, 4.5, 3, 2.9, 1.5),
off = as.logical(c("F", "F", "T", "T", "F")),
hiOnTarget = c(5.5, 4, 5, 4.7, 4),
loOnTarget =c(4, 3, 3, 4, 3),
hiOffTarget = c(2, 3, 4, 2, 3),
lowOffTarget = c(1, 2, 1, 1.2, 2),
extremeValue = as.logical(c("F", "T", "F", "T", "T")))


My attempts to generate the sixth column, extremeValue, have been centered on if(){}else{} style logical statements, the closest of which is currently:



exampleWanted <- if( exampleCurrent$value > exampleCurrent$hiOnTarget | exampleCurrent$value > exampleCurrent$loOnTarget) {
exampleWanted <-"True"
} else {
exampleWanted <-"False"}


I've obviously only got half way here as this will blindly assess the calculation as entirely 'on', however I can't even get this part to work. I am planning to use switch() to toggle between two similar if(){}else{} commands, though totally alternative solutions would be fine.


N.B. This is a small the first major R script I've ever written outside of a tutorial, so apologies for what is probably practically a simple question.


Aucun commentaire:

Enregistrer un commentaire