creating new variables with transform and %>%

dplyr, magrittr, r

Solution

You can, if you want:

expand.grid(a=1000+c(-500, 0, 500), b=c(15,150)) %>%
mutate(c = a %>% seq_along %>% LETTERS[.] %>% paste0("foo_", .))

Problem

I'm trying to use the "pipe-like" operator to create a new variable, the same length as others in the dataframe, based on the `LETTERS` vector. Something is going wrong, and I am too new to `magrittr` to diagnose the problem. I am able to create the variable correctly when I try with some "traditional" nested functions: ``` expand.grid(a=c(1000-500,1000,1000+500), b=c(15,150)) %>% mutate(c=paste("foo", LETTERS[seq_along(a)],sep="_")) ## a b c ## 1 500 15 foo_A ## 2 1000 15 foo_B ## 3 1500 15 foo_C ## 4 500 150 foo_D ## 5 1000 150 foo_E ## 6 1500 150 foo_F ``` So then I thought I'd try with the pipelike `%>%` from `magrittr` and `dplyr` ``` expand.grid(a=c(1000-500,1000,1000+500), b=c(15,150)) %>% mutate(c=paste("foo", a %>% seq_along %>% LETTERS[.],sep="_")) ## Error: incorrect number of dimensions ``` This also does not work when I add the aliased extract (`[`) function from `magrittr`: ``` expand.grid(a=c(1000-500,1000,1000+500), b=c(15,150)) %>% mutate(c=paste("foo", a %>% seq_along %>% extract(LETTERS,.), sep="_")) ## Error: incorrect number of dimensions ``` I've tried debugging the pipe with `debug_pipe` to no avail. I'd be very grateful for any ideas!

Original source