Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: switch statement with multiple lines

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))
}
like image 784
user1481829 Avatar asked Feb 02 '26 07:02

user1481829


1 Answers

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
like image 68
David Robinson Avatar answered Feb 03 '26 23:02

David Robinson