Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

switch statement giving unexpected ',' error

I am trying to create a simple switch to determine start date based on quarter.

My code is below:

qtr_start <- function(qtr, yr){
  switch(qtr,
         1 = paste(yr, "0101", sep = ""),
         2 = paste(yr, "0104", sep = ""),
         3 = paste(yr, "0107", sep = ""),
         4 = paste(yr, "0110", sep = ""))
}

This gives the error:

Error: unexpected '=' in:
"switch(qtr,
         1 ="
>          2 = paste(yr, "0104", sep = ""),
Error: unexpected ',' in "         2 = paste(yr, "0104", sep = ""),"
>          3 = paste(yr, "0107", sep = ""),
Error: unexpected ',' in "         3 = paste(yr, "0107", sep = ""),"
>          4 = paste(yr, "0110", sep = ""))
Error: unexpected ')' in "         4 = paste(yr, "0110", sep = ""))"

I am really struggling to see how this is different from the help version:

centre <- function(x, type) {
  switch(type,
         mean = mean(x),
         median = median(x),
         trimmed = mean(x, trim = .1))
}

All help appreciated!

like image 961
Preston Avatar asked Jul 16 '26 00:07

Preston


1 Answers

You can't use numbers as the names of cases. Just leave them away (R will use the first case for 1, the second for 2 and so on, or use strings [edit] and use as.character on the number.

So either

 qtr_start <- function(qtr, yr){
     switch(qtr,
        paste(yr, "0101", sep = ""),
        paste(yr, "0104", sep = ""),
        paste(yr, "0107", sep = ""),
        paste(yr, "0110", sep = "")) }

or

qtr_start <- function(qtr, yr){
  switch(as.character(qtr),
         "1" = paste(yr, "0101", sep = ""),
         "2" = paste(yr, "0104", sep = ""),
         "3" = paste(yr, "0107", sep = ""),
         "4" = paste(yr, "0110", sep = ""))
}
like image 119
Christoph Wolk Avatar answered Jul 18 '26 14:07

Christoph Wolk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!