Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

else clause in map_if #324

Closed
GuiMarthe opened this issue May 11, 2017 · 7 comments
Closed

else clause in map_if #324

GuiMarthe opened this issue May 11, 2017 · 7 comments
Labels
feature a feature request or enhancement map 🗺️

Comments

@GuiMarthe
Copy link

I fell that i order for the map_if function to be really useful should have the possibility of calling an "else" function if the outcome of .predicate is false.

By default it should leave the object iterated alone, and not return anything.

@lionel-
Copy link
Member

lionel- commented May 11, 2017

I don't think that will happen because ... can only be forwarded in one function. To deal with this I usually do it that way:

cnd <- map_lgl(x, predicate)
x <- map_if(x, cnd, fun1)
x <- map_if(x, !cnd, fun2)

@GuiMarthe
Copy link
Author

Yes yes that is a possible solution. But it would be more concise if one could do it in one line, like>
x <- map_if(x, cnd, fun1, fun2)
Also, it makes sense since it sort of resembles ifelse and if_else

@lionel-
Copy link
Member

lionel- commented May 11, 2017

in purrr's syntax, fun2 is passed to fun1 in your example.

@hadley
Copy link
Member

hadley commented May 14, 2017

We could have map_if_else(.x, .cnd, .true, .false, ...)

@lionel-
Copy link
Member

lionel- commented May 14, 2017

without the dots?

@hadley
Copy link
Member

hadley commented May 14, 2017

We could still have dots, but they'd be passed to both .true and .false so they wouldn't be that useful. Should probably have .na too, for completeness.

@hadley hadley added the feature a feature request or enhancement label Feb 5, 2018
@Athospd
Copy link

Athospd commented Feb 16, 2018

Why the following solution is not viable?

map_if_else <- function (.x, .p, .true, .false, .na = identity, ...) {
  
  sel <- purrr:::probe(.x, .p)
  out <- list_along(.x)
  out[which(sel)] <- map(.x[which(sel)], .true, ...)
  out[which(!sel)] <- map(.x[which(!sel)], .false, ...)
  out[is.na(sel)] <- map(.x[is.na(sel)], .na, ...)
  
  set_names(out, names(.x))
}

regards

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature a feature request or enhancement map 🗺️
Projects
None yet
Development

No branches or pull requests

4 participants