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

Comments

Projects
None yet
4 participants
@GuiMarthe
Copy link

GuiMarthe commented May 11, 2017

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-

This comment has been minimized.

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

This comment has been minimized.

Copy link

GuiMarthe commented May 11, 2017

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-

This comment has been minimized.

Copy link
Member

lionel- commented May 11, 2017

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

@hadley

This comment has been minimized.

Copy link
Member

hadley commented May 14, 2017

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

@lionel-

This comment has been minimized.

Copy link
Member

lionel- commented May 14, 2017

without the dots?

@hadley

This comment has been minimized.

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 label Feb 5, 2018

@lionel- lionel- added the help-wanted label Feb 14, 2018

@Athospd

This comment has been minimized.

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

@hadley hadley added map 🗺 and removed help-wanted labels May 5, 2018

lionel- added a commit to lionel-/lowliner that referenced this issue Nov 30, 2018

lionel- added a commit to lionel-/lowliner that referenced this issue Nov 30, 2018

@lionel- lionel- closed this in #592 Nov 30, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment