3

I can't find a way to return multiple values (columns) or just a tibble from case_when().

input <- tibble(a = c(1, 2, 3))

input %>%
  mutate(
    case =
      case_when(
        a == 1 ~ tibble(x = "case1", y = "c1"),
        a == 2 ~ tibble(x = "case2", y = "c2"),
        a == 3 ~ tibble(x = "case3", y = "c3")
        )
    )

How can I set multiple parameters depending on some regex conditions?

Piotr K
  • 943
  • 9
  • 20

2 Answers2

5

We can return a list column as mutate expects the regular column to be a vector with length same as the number of rows of original data

input %>%
  mutate(
  case =
    case_when(
      a == 1 ~ list(tibble(x = "case1", y = "c1")),
      a == 2 ~ list(tibble(x = "case2", y = "c2")),
     a == 3 ~ list(tibble(x = "case3", y = "c3"))
     )
 )

-output

# A tibble: 3 x 2
#      a case            
#  <dbl> <list>          
#1     1 <tibble [1 × 2]>
#2     2 <tibble [1 × 2]>
#3     3 <tibble [1 × 2]>
akrun
  • 874,273
  • 37
  • 540
  • 662
1

This is a weird situation. I think it is better to put your multiple values in separate columns. You can do that with a datastep() function:

library(tibble)
library(libr)

# Create sample data
input <- tibble(a = c(1, 2, 3), b = c("a", "b", "c"))

# Execute datastep
input2 <- input %>%
  datastep(keep = c("a", "b", "x", "y"),
    {
      if (a == 1) {
        x <- "case1"
        y <- "c1"
      } else if (a == 2) {
        x <- "case2"
        y <- "c2"
      } else if (a == 3) {
        x <- "case3"
        y <- "c3"
      }
    })

# View results
input2
# # A tibble: 3 x 4
#       a b     x     y    
#   <dbl> <chr> <chr> <chr>
# 1     1 a     case1 c1   
# 2     2 b     case2 c2   
# 3     3 c     case3 c3 
David J. Bosak
  • 1,386
  • 12
  • 22