Reputation: 37
I feel a bit embarrassed to ask that rather simple question but I'm searching for a couple of hours now and can't get my head around.
I'm trying to build a switch for my function:
output <- "both"
if (output== "both" | "partone")
{cat("partone")}
if (output=="both" | "parttwo")
{cat("parttwo")}
This should produce partone
and parttwo
. Whereasoutput <- "partone"
just partone
.
How could this work?
Upvotes: 2
Views: 55
Reputation: 291
Use something like this.
if (output %in% c("both","partone"))
{cat("partone")}
if (output %in% c("both","parttwo"))
{cat("parttwo")}
It will produce your desired output.
Upvotes: 3
Reputation: 887148
If we check the logical condition
output== "both" | "partone"
Error in output == "both" | "partone" : operations are possible only for numeric, logical or complex types
As we need to check for either 'both' or 'partone', use the %in%
on a vector
of string elements
output %in% c('both', 'partone')
#[1] TRUE
Now, create a function for reusability
f1 <- function(out, vec) {
if(out %in% vec) cat(setdiff(vec, 'both'), '\n')
}
output <- 'both'
f1(output, c('both', 'partone'))
#partone
f1(output, c('both', 'parttwo'))
#parttwo
output <- 'partone'
f1(output, c('both', 'partone'))
#partone
f1(output, c('both', 'parttwo'))
Upvotes: 2
Reputation: 124646
This syntax is incorrect:
if (output== "both" | "partone") {cat("partone")}
You can write like this:
if (output == "both" || output == "partone")
{cat("partone")}
Or like this:
if (output %in% c("both", "partone"))
{cat("partone")}
Upvotes: 2