I am trying to calculate some simple ratios and use R’s bracket notation to denote the baseline for the ratio.
Now I am struggling with defining a function that lets me parameterize the baseline.
I don’t want to hardcode it, since I have a couple of those. And, I really don’t understand what R is exactly doing and am very curious how to achieve the desired behavior.
Here some code based on example data:
data("singer", package = "lattice")
# this is what I want, but what currently doesn't work
my_ratio <- function(voice) {
ddply(singer, ~ voice.part,
transform,
# how do I refer to the voice variable here?
# it looks like it misunderstands it as column?
ratio = height / mean(height[voice.part == voice]))
}
# this version works with a hardcoded voice part
my_ratio_hard <- function() {
ddply(singer, ~ voice.part,
transform,
ratio = height / mean(height[voice.part == "Soprano 1"]))
}
How about this:
Did you really only want to scale the rows matching
voiceand haveNaNelsewhere (that’s also what your hard-coded function does)?A more compact version of the above:
and if you actually want to scale all the records (as your comment suggests):