In R: I have a matrix with one column classified by 8 types: a, b, c, d, e, f, g, h. I need to do different computations for each type using the data in the other columns. I want to use a switch() function to automate the looping through each type and state the difference calculations for each type; HOWEVER, everything I am seeing online only shows examples of the syntax for one line switch computations for each switch.
Here is an example using the code provided in the switch() help. I know that mean() is a function, but let's just say for this example, that it isn't a function, because I just want to illustrate that I do not know the syntax (and it's not clearly stated in my research online):
centre <- function(x, type) {
switch(type,
mean = {
total.sum<-sum(type)
mean = total.sum/length(type)
},
median = median(x),
trimmed = mean(x, trim = .1))
}
I think the miscommunication is coming from a typo in your example:
mean = {
total.sum<-sum(type)
mean = total.sum/length(type)
},
should be
mean = {
total.sum<-sum(x)
mean = total.sum/length(x)
},
If you make this change, it behaves exactly how you would expect it to.
ETA: I'm not sure what the issue is in your comment. Please try the following code:
set.seed(1)
centre <- function(x, type) {
switch(type,
mean = {
total.sum<-sum(x)
mean = total.sum/length(x)
},
median = median(x),
trimmed = mean(x, trim = .1))
}
x <- rcauchy(10)
print(centre(x, "mean"))
print(centre(x, "median"))
print(centre(x, "trimmed"))
The output is:
[1] -0.4844658
[1] -0.236111
[1] -0.3632328
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With