Using seperate in tidyr conditionally using ifelse

I am trying to seperate a column into multiple columns using tidyr. I tried initially using if..else and it wouldnt work and when I looked at stackoverflow the suggestion was to use ifelse. So I tried using ifelse and it still doessnt work. Below is what I am trying to do when I am getting the error :

testdata <- tibble::tribble(
  ~config,       ~construct, ~var,
  1, "This_is_line_1",   12,
  2, "This_is_dot_2",   15,
  3, "This_is_dot_1 ",   15,
  4, "This_is_line_2",   12,
  5, "This_is_line_3",   12,
  6, "This_is_dot_4",   15,
  7, "This_is_dot_3 ",   15,
  8, "This_is_line_4",   12
)


  ifelse(testdata$var == 12,
         tidyr::separate(testdata$construct, into = c("etc1","etc2", "etc3","etc4"), sep = "_", remove = FALSE),
         tidyr::separate(testdata$construct, into = c("etc1","etc2", "etc5","etc4"), sep = "_", remove = FALSE)
         )

Error message : Error in UseMethod("separate_") : no applicable method for 'separate_' applied to an object of class "character"

Thank you.

I don't think you can nest separate inside if_else. How about if you do separate first, and then adjust the answer based on var?

library(dplyr)
library(tidyr)

testdata <- tibble::tribble(
  ~config,       ~construct, ~var,
  1, "This_is_line_1",   12,
  2, "This_is_dot_2",   15,
  3, "This_is_dot_1 ",   15,
  4, "This_is_line_2",   12,
  5, "This_is_line_3",   12,
  6, "This_is_dot_4",   15,
  7, "This_is_dot_3 ",   15,
  8, "This_is_line_4",   12
)

testdata %>% 
  tidyr::separate(construct, into = c("etc1","etc2", "etc3","etc4"), sep = "_", remove = FALSE) %>% 
  mutate(
    etc5 = if_else(var == 12, NA_character_, etc3),
    etc3 = if_else(var == 12, etc3, NA_character_)
    )
#> # A tibble: 8 x 8
#>   config construct        etc1  etc2  etc3  etc4    var etc5 
#>    <dbl> <chr>            <chr> <chr> <chr> <chr> <dbl> <chr>
#> 1      1 "This_is_line_1" This  is    line  "1"      12 <NA> 
#> 2      2 "This_is_dot_2"  This  is    <NA>  "2"      15 dot  
#> 3      3 "This_is_dot_1 " This  is    <NA>  "1 "     15 dot  
#> 4      4 "This_is_line_2" This  is    line  "2"      12 <NA> 
#> 5      5 "This_is_line_3" This  is    line  "3"      12 <NA> 
#> 6      6 "This_is_dot_4"  This  is    <NA>  "4"      15 dot  
#> 7      7 "This_is_dot_3 " This  is    <NA>  "3 "     15 dot  
#> 8      8 "This_is_line_4" This  is    line  "4"      12 <NA>

Created on 2020-07-15 by the reprex package (v0.3.0)

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.