Brani Brani - 3 years ago 197
R Question

Using `paste` inside dplyr::transmute

"For which digits

x
and
y
the number whose representation in the Decimal numeral system is
6x12y
is divided by
45
?"

The following is not of course the solution that discussed with my doughter, but an attempt to test my skills in R. However, the last line doesn't do what I want.

library(tidyverse)
library(stringi)

replicate(2, 0:9, simplify = FALSE) %>%
expand.grid() %>%
as.tibble() %>%
transmute(newcol=do.call(paste0,list(6,Var1,12,Var2))) %>%
map_df(as.numeric) %>%
filter(newcol%%45==0) %>%
transmute(x_y=paste(stri_sub(newcol,c(2,5),c(2,5)),collapse = " "))


I got the desired result using this. But what is my mistake in the previous one?

replicate(2, 0:9, simplify = FALSE) %>%
expand.grid() %>%
as.tibble() %>%
transmute(newcol=do.call(paste0,list(6,Var1,12,Var2))) %>%
map_df(as.numeric) %>%
filter(newcol%%45==0) %>%
transmute(x_y=map2_chr(stri_sub(newcol,2,2),stri_sub(newcol,5,5),paste))

Answer Source

You need to to your operation rowwise. Thus, adding the rowwise() condition in your pipe will fix it, i.e.

library(tidyverse)

replicate(2, 0:9, simplify = FALSE) %>% 
    expand.grid() %>% 
    as.tibble() %>% 
    transmute(newcol=do.call(paste0,list(6,Var1,12,Var2))) %>% 
    map_df(as.numeric) %>% 
    filter(newcol%%45==0) %>% 
    rowwise() %>% # <--- Added the rowwise
    transmute(x_y=paste(stri_sub(newcol,c(2,5),c(2,5)),collapse = " "))

Which gives the expected result,

Source: local data frame [3 x 1]
Groups: <by row>

# A tibble: 3 x 1
    x_y
  <chr>
1   0 0
2   9 0
3   4 5
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download