简体   繁体   中英

Using `map`instead of `apply` inside dplyr::mutate

"Which 4-digit number, multiplied by 4, gives itself reversed?"

Here is an attempt to solve this relatively easy math problem, using R

library(tidyverse)
library(stringi)

expand.grid(replicate(4, 0:9, simplify = FALSE)) %>%
  filter(Var1 !=0, Var4 !=0) %>%
  transmute(newcol=as.numeric(do.call(paste0,.))) %>%
  filter(newcol<2500) %>% 
  mutate(newcol2=4*newcol) %>% 
  filter(newcol==stri_reverse(newcol2))

A second approach was this:

expand.grid(replicate(4, 0:9, simplify = FALSE)) %>%
  filter(Var1 !=0, Var4 !=0) %>%
  transmute(newcol=as.numeric(do.call(paste0,.))) %>%
  filter(newcol<2500) %>% 
  mutate(newcol2=4*newcol) %>% 
  filter(newcol==apply(.[c("newcol2")],1,function(x) paste0(floor(x/ 10^(0:(nchar(x) - 1))) %% 10,collapse=""))) 

Can you show me how to use purrr::map instead of apply in the final step?

You can change the last filter call to the following.

filter(newcol == map(newcol2, ~paste0(floor(./ 10^(0:(nchar(.) - 1))) %% 10, collapse = "")))

or this

filter(newcol == map_chr(newcol2, ~paste0(floor(./ 10^(0:(nchar(.) - 1))) %% 10, collapse = "")))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM