Case Statement Equivalent in R

Case When LIKE equivalent in R

Actually not sure if I got the question right but if you mean you want to test if "Alpha" is in the column Letter-Test, then this works:

    > df <- data.frame("Letter-Test" = c("Alpha - Test", "Beta- Test", "Zeta-Test", "Alpha-Two", "Beta-Two"),
+ stringsAsFactors = FALSE)
>
> ifelse(test = grepl("Alpha", df$Letter.Test), yes = "Alpha", no = df$Letter.Test)
[1] "Alpha" "Beta- Test" "Zeta-Test" "Alpha" "Beta-Two"

Test takes TRUE and FALSE, grepl returns TRUE if the word was found inside the column Letter.Test.

Or you can put the results directly into a new column in the data frame:

> df$AplhaTest <- ifelse(test = grepl("Alpha", df$Letter.Test), yes = "Alpha", no = df$Letter.Test)
> df
Letter.Test AplhaTest
1 Alpha - Test Alpha
2 Beta- Test Beta- Test
3 Zeta-Test Zeta-Test
4 Alpha-Two Alpha
5 Beta-Two Beta-Two

CASE WHEN equivalent in R for a vector

matrix$Age3 <- ifelse(!is.na(matrix$Age),matrix$Age,matrix$Age2)

data.table alternative for dplyr case_when

FYI, a more recent answer for those coming across this post 2019. data.table versions above 1.13.0 have the fcase function that can be used. Note that it is not a drop-in replacement for dplyr::case_when as the syntax is different, but will be a "native" data.table way of calculation.

# Lazy evaluation
x = 1:10
data.table::fcase(
x < 5L, 1L,
x >= 5L, 3L,
x == 5L, stop("provided value is an unexpected one!")
)
# [1] 1 1 1 1 3 3 3 3 3 3

dplyr::case_when(
x < 5L ~ 1L,
x >= 5L ~ 3L,
x == 5L ~ stop("provided value is an unexpected one!")
)
# Error in eval_tidy(pair$rhs, env = default_env) :
# provided value is an unexpected one!

# Benchmark
x = sample(1:100, 3e7, replace = TRUE) # 114 MB
microbenchmark::microbenchmark(
dplyr::case_when(
x < 10L ~ 0L,
x < 20L ~ 10L,
x < 30L ~ 20L,
x < 40L ~ 30L,
x < 50L ~ 40L,
x < 60L ~ 50L,
x > 60L ~ 60L
),
data.table::fcase(
x < 10L, 0L,
x < 20L, 10L,
x < 30L, 20L,
x < 40L, 30L,
x < 50L, 40L,
x < 60L, 50L,
x > 60L, 60L
),
times = 5L,
unit = "s")
# Unit: seconds
# expr min lq mean median uq max neval
# dplyr::case_when 11.57 11.71 12.22 11.82 12.00 14.02 5
# data.table::fcase 1.49 1.55 1.67 1.71 1.73 1.86 5

Source, data.table NEWS for 1.13.0, released (24 Jul 2020).

switch case: several equivalent cases expressions in r

My personal choice would be to remap your k to the overlapping cases. Example:

k<-1:20
kmatch<-(k-1)%%9 +1
# [1] 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2

Then feed kmatch to your case expression

How to use the switch statement in R functions?

Well, switch probably wasn't really meant to work like this, but you can:

AA = 'foo'
switch(AA,
foo={
# case 'foo' here...
print('foo')
},
bar={
# case 'bar' here...
print('bar')
},
{
print('default')
}
)

...each case is an expression - usually just a simple thing, but here I use a curly-block so that you can stuff whatever code you want in there...



Related Topics



Leave a reply



Submit