I am new to R programming. I don't know whether we could use switch statements for numerical objects.
This is my code,
myfunction <- function() {
x <- 10
switch(x,
1={
print("one")
},
2={
print("two")
},
3={
print("three")
},
{
print("default") #Edited one..
}
)
}
I got this error,
test.R:4:18: unexpected '='
3: switch(x,
4: 1=
^
Please help me out this problem.
To take full advantage of switch
's functionality (in particular its ability to handle arbitrary values with a final "default" expression) and to handle numbers other than 1,2,3,..., you'd be better off converting any input to a character string.
I would do something like this:
myfunction <- function(x) {
switch(as.character(x),
"1" = print("one"),
"2" = print("two"),
"3" = print("three"),
print("something other than 'one', 'two', or 'three'"))
}
myfunction(1)
# [1] "one"
myfunction(345)
# [1] "something other than 'one', 'two', or 'three'"
myfunction <- function(x) {
switch(x,
print("one"),
print("two"),
print("three"))}
myfunction(1)
## [1] "one"
Edit: As mentioned in comments, this method isn't evaluating the values that are being entered, rather uses them as an index. Thus, it works in your case but it won't work if the statements were to be reordered (see @Joshs answer for better approach).
Either way, I don't think switch
is the right function to use in this case, because it is mainly meant for switching between different alternatives, while in your case, you are basically running the same function over and over. Thus, adding extra a statement for each alternative seems like too much work (if you, for example, wanted to display 20 different numbers, you'll have to write 20 different statements).
Instead, you could try the english
package which will allow you to display as many numbers as you will define in the ifelse
statement
library(english)
myfunction2 <- function(x) {
ifelse(x %in% 1:3,
as.character(as.english(x)),
"default")}
myfunction2(1)
## [1] "one"
myfunction2(4)
## [1] "default"
Alternatively, you could also avoid using switch
(though not necessarily recommended) by using match
myfunction3 <- function(x) {
df <- data.frame(A = 1:3, B = c("one", "two", "three"), stringsAsFactors = FALSE)
ifelse(x %in% 1:3,
df$B[match(x, df$A)],
"default")}
myfunction3(1)
## [1] "one"
myfunction3(4)
## [1] "default"
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