Using purrr::pmap() in a rowwise manner outside of mutate()












0















I am trying to use purrr::pmap() to apply a custom function in a rowwise fashion along some dataframe rows. I can achieve my desired end result with a for-loop and with apply(), but when I try to use pmap() I can only get the result I want in combination with mutate(), which in my real-life applied case will be insufficient.



Is there a way to use pmap() to apply my custom function and just have the output print rather than be stored in a new column?



library(dplyr)
library(purrr)
library(tibble)


Create demo data & custom function



set.seed(57)

ds_mt <-
mtcars %>%
rownames_to_column("model") %>%
mutate(
am = factor(am, labels = c("auto", "manual")),
vs = factor(vs, labels = c("V", "S"))
) %>%
select(model, mpg, wt, cyl, am, vs) %>%
sample_n(3)

foo <- function(model, am, mpg){
print(
paste("The", model, "has a", am, "transmission and gets", mpg, "mpgs.")
)
}


Successful example of rowwise for-loop:



for (row in 1:nrow(ds_mt)) {
foo(
model = ds_mt[row, "model"],
am = ds_mt[row, "am"],
mpg = ds_mt[row, "mpg"]
)
}


Successful example using apply():



row.names(ds_mt) <- NULL # to avoid named vector as output

apply(
ds_mt,
MARGIN = 1,
FUN = function(ds)
foo(
model = ds["model"],
am = ds["am"],
mpg = ds["mpg"]
)
)


Example using pmap() within mutate() that is almost what I need.



ds_mt %>% 
mutate(new_var =
pmap(
.l =
list(
model = model,
am = am,
mpg = mpg
),
.f = foo
))


FAILING CODE: Why doesn't this work?



ds_mt %>% 
pmap(
.l =
list(
model = model,
am = am,
mpg = mpg
),
.f = foo
)









share|improve this question























  • Please note that paste is vectorized, so no need for various row-wise operations. with(mtcars[1:3, ], paste("The", vs, "has a", am, "transmission and gets", mpg, "mpgs.")). Perhaps this was a toy example and you have a 'real' function which isn't vectorized?

    – Henrik
    Nov 20 '18 at 23:35








  • 1





    You are passing ds_mt to any of the arguments in pmap() in your current code. You could select the columns you want and then pass that object to .l. Like ds_mt %>% select(model, am, mpg) %>% pmap(foo) (although as others have pointed out you don't need this for this particular task.)

    – aosmith
    Nov 20 '18 at 23:54


















0















I am trying to use purrr::pmap() to apply a custom function in a rowwise fashion along some dataframe rows. I can achieve my desired end result with a for-loop and with apply(), but when I try to use pmap() I can only get the result I want in combination with mutate(), which in my real-life applied case will be insufficient.



Is there a way to use pmap() to apply my custom function and just have the output print rather than be stored in a new column?



library(dplyr)
library(purrr)
library(tibble)


Create demo data & custom function



set.seed(57)

ds_mt <-
mtcars %>%
rownames_to_column("model") %>%
mutate(
am = factor(am, labels = c("auto", "manual")),
vs = factor(vs, labels = c("V", "S"))
) %>%
select(model, mpg, wt, cyl, am, vs) %>%
sample_n(3)

foo <- function(model, am, mpg){
print(
paste("The", model, "has a", am, "transmission and gets", mpg, "mpgs.")
)
}


Successful example of rowwise for-loop:



for (row in 1:nrow(ds_mt)) {
foo(
model = ds_mt[row, "model"],
am = ds_mt[row, "am"],
mpg = ds_mt[row, "mpg"]
)
}


Successful example using apply():



row.names(ds_mt) <- NULL # to avoid named vector as output

apply(
ds_mt,
MARGIN = 1,
FUN = function(ds)
foo(
model = ds["model"],
am = ds["am"],
mpg = ds["mpg"]
)
)


Example using pmap() within mutate() that is almost what I need.



ds_mt %>% 
mutate(new_var =
pmap(
.l =
list(
model = model,
am = am,
mpg = mpg
),
.f = foo
))


FAILING CODE: Why doesn't this work?



ds_mt %>% 
pmap(
.l =
list(
model = model,
am = am,
mpg = mpg
),
.f = foo
)









share|improve this question























  • Please note that paste is vectorized, so no need for various row-wise operations. with(mtcars[1:3, ], paste("The", vs, "has a", am, "transmission and gets", mpg, "mpgs.")). Perhaps this was a toy example and you have a 'real' function which isn't vectorized?

    – Henrik
    Nov 20 '18 at 23:35








  • 1





    You are passing ds_mt to any of the arguments in pmap() in your current code. You could select the columns you want and then pass that object to .l. Like ds_mt %>% select(model, am, mpg) %>% pmap(foo) (although as others have pointed out you don't need this for this particular task.)

    – aosmith
    Nov 20 '18 at 23:54
















0












0








0








I am trying to use purrr::pmap() to apply a custom function in a rowwise fashion along some dataframe rows. I can achieve my desired end result with a for-loop and with apply(), but when I try to use pmap() I can only get the result I want in combination with mutate(), which in my real-life applied case will be insufficient.



Is there a way to use pmap() to apply my custom function and just have the output print rather than be stored in a new column?



library(dplyr)
library(purrr)
library(tibble)


Create demo data & custom function



set.seed(57)

ds_mt <-
mtcars %>%
rownames_to_column("model") %>%
mutate(
am = factor(am, labels = c("auto", "manual")),
vs = factor(vs, labels = c("V", "S"))
) %>%
select(model, mpg, wt, cyl, am, vs) %>%
sample_n(3)

foo <- function(model, am, mpg){
print(
paste("The", model, "has a", am, "transmission and gets", mpg, "mpgs.")
)
}


Successful example of rowwise for-loop:



for (row in 1:nrow(ds_mt)) {
foo(
model = ds_mt[row, "model"],
am = ds_mt[row, "am"],
mpg = ds_mt[row, "mpg"]
)
}


Successful example using apply():



row.names(ds_mt) <- NULL # to avoid named vector as output

apply(
ds_mt,
MARGIN = 1,
FUN = function(ds)
foo(
model = ds["model"],
am = ds["am"],
mpg = ds["mpg"]
)
)


Example using pmap() within mutate() that is almost what I need.



ds_mt %>% 
mutate(new_var =
pmap(
.l =
list(
model = model,
am = am,
mpg = mpg
),
.f = foo
))


FAILING CODE: Why doesn't this work?



ds_mt %>% 
pmap(
.l =
list(
model = model,
am = am,
mpg = mpg
),
.f = foo
)









share|improve this question














I am trying to use purrr::pmap() to apply a custom function in a rowwise fashion along some dataframe rows. I can achieve my desired end result with a for-loop and with apply(), but when I try to use pmap() I can only get the result I want in combination with mutate(), which in my real-life applied case will be insufficient.



Is there a way to use pmap() to apply my custom function and just have the output print rather than be stored in a new column?



library(dplyr)
library(purrr)
library(tibble)


Create demo data & custom function



set.seed(57)

ds_mt <-
mtcars %>%
rownames_to_column("model") %>%
mutate(
am = factor(am, labels = c("auto", "manual")),
vs = factor(vs, labels = c("V", "S"))
) %>%
select(model, mpg, wt, cyl, am, vs) %>%
sample_n(3)

foo <- function(model, am, mpg){
print(
paste("The", model, "has a", am, "transmission and gets", mpg, "mpgs.")
)
}


Successful example of rowwise for-loop:



for (row in 1:nrow(ds_mt)) {
foo(
model = ds_mt[row, "model"],
am = ds_mt[row, "am"],
mpg = ds_mt[row, "mpg"]
)
}


Successful example using apply():



row.names(ds_mt) <- NULL # to avoid named vector as output

apply(
ds_mt,
MARGIN = 1,
FUN = function(ds)
foo(
model = ds["model"],
am = ds["am"],
mpg = ds["mpg"]
)
)


Example using pmap() within mutate() that is almost what I need.



ds_mt %>% 
mutate(new_var =
pmap(
.l =
list(
model = model,
am = am,
mpg = mpg
),
.f = foo
))


FAILING CODE: Why doesn't this work?



ds_mt %>% 
pmap(
.l =
list(
model = model,
am = am,
mpg = mpg
),
.f = foo
)






r purrr pmap






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 20 '18 at 23:27









JoeJoe

733615




733615













  • Please note that paste is vectorized, so no need for various row-wise operations. with(mtcars[1:3, ], paste("The", vs, "has a", am, "transmission and gets", mpg, "mpgs.")). Perhaps this was a toy example and you have a 'real' function which isn't vectorized?

    – Henrik
    Nov 20 '18 at 23:35








  • 1





    You are passing ds_mt to any of the arguments in pmap() in your current code. You could select the columns you want and then pass that object to .l. Like ds_mt %>% select(model, am, mpg) %>% pmap(foo) (although as others have pointed out you don't need this for this particular task.)

    – aosmith
    Nov 20 '18 at 23:54





















  • Please note that paste is vectorized, so no need for various row-wise operations. with(mtcars[1:3, ], paste("The", vs, "has a", am, "transmission and gets", mpg, "mpgs.")). Perhaps this was a toy example and you have a 'real' function which isn't vectorized?

    – Henrik
    Nov 20 '18 at 23:35








  • 1





    You are passing ds_mt to any of the arguments in pmap() in your current code. You could select the columns you want and then pass that object to .l. Like ds_mt %>% select(model, am, mpg) %>% pmap(foo) (although as others have pointed out you don't need this for this particular task.)

    – aosmith
    Nov 20 '18 at 23:54



















Please note that paste is vectorized, so no need for various row-wise operations. with(mtcars[1:3, ], paste("The", vs, "has a", am, "transmission and gets", mpg, "mpgs.")). Perhaps this was a toy example and you have a 'real' function which isn't vectorized?

– Henrik
Nov 20 '18 at 23:35







Please note that paste is vectorized, so no need for various row-wise operations. with(mtcars[1:3, ], paste("The", vs, "has a", am, "transmission and gets", mpg, "mpgs.")). Perhaps this was a toy example and you have a 'real' function which isn't vectorized?

– Henrik
Nov 20 '18 at 23:35






1




1





You are passing ds_mt to any of the arguments in pmap() in your current code. You could select the columns you want and then pass that object to .l. Like ds_mt %>% select(model, am, mpg) %>% pmap(foo) (although as others have pointed out you don't need this for this particular task.)

– aosmith
Nov 20 '18 at 23:54







You are passing ds_mt to any of the arguments in pmap() in your current code. You could select the columns you want and then pass that object to .l. Like ds_mt %>% select(model, am, mpg) %>% pmap(foo) (although as others have pointed out you don't need this for this particular task.)

– aosmith
Nov 20 '18 at 23:54














1 Answer
1






active

oldest

votes


















0














So after some more reading it seems this is a case for pwalk() rather than pmap(), because I am trying to get output to print (i.e., a side effect) rather than to be stored in a dataframe.



library(dplyr)
library(purrr)
library(tibble)

set.seed(57)

ds_mt <-
mtcars %>%
rownames_to_column("model") %>%
mutate(
am = factor(am, labels = c("auto", "manual")),
vs = factor(vs, labels = c("V", "S"))
) %>%
select(model, mpg, wt, cyl, am, vs) %>%
sample_n(3)

foo <- function(model, am, mpg){
print(
paste("The", model, "has a", am, "transmission and gets", mpg, "mpgs.")
)
}

ds_mt %>%
select(model, am, mpg) %>%
pwalk(
.l = .,
.f = foo
)





share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53403156%2fusing-purrrpmap-in-a-rowwise-manner-outside-of-mutate%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    So after some more reading it seems this is a case for pwalk() rather than pmap(), because I am trying to get output to print (i.e., a side effect) rather than to be stored in a dataframe.



    library(dplyr)
    library(purrr)
    library(tibble)

    set.seed(57)

    ds_mt <-
    mtcars %>%
    rownames_to_column("model") %>%
    mutate(
    am = factor(am, labels = c("auto", "manual")),
    vs = factor(vs, labels = c("V", "S"))
    ) %>%
    select(model, mpg, wt, cyl, am, vs) %>%
    sample_n(3)

    foo <- function(model, am, mpg){
    print(
    paste("The", model, "has a", am, "transmission and gets", mpg, "mpgs.")
    )
    }

    ds_mt %>%
    select(model, am, mpg) %>%
    pwalk(
    .l = .,
    .f = foo
    )





    share|improve this answer




























      0














      So after some more reading it seems this is a case for pwalk() rather than pmap(), because I am trying to get output to print (i.e., a side effect) rather than to be stored in a dataframe.



      library(dplyr)
      library(purrr)
      library(tibble)

      set.seed(57)

      ds_mt <-
      mtcars %>%
      rownames_to_column("model") %>%
      mutate(
      am = factor(am, labels = c("auto", "manual")),
      vs = factor(vs, labels = c("V", "S"))
      ) %>%
      select(model, mpg, wt, cyl, am, vs) %>%
      sample_n(3)

      foo <- function(model, am, mpg){
      print(
      paste("The", model, "has a", am, "transmission and gets", mpg, "mpgs.")
      )
      }

      ds_mt %>%
      select(model, am, mpg) %>%
      pwalk(
      .l = .,
      .f = foo
      )





      share|improve this answer


























        0












        0








        0







        So after some more reading it seems this is a case for pwalk() rather than pmap(), because I am trying to get output to print (i.e., a side effect) rather than to be stored in a dataframe.



        library(dplyr)
        library(purrr)
        library(tibble)

        set.seed(57)

        ds_mt <-
        mtcars %>%
        rownames_to_column("model") %>%
        mutate(
        am = factor(am, labels = c("auto", "manual")),
        vs = factor(vs, labels = c("V", "S"))
        ) %>%
        select(model, mpg, wt, cyl, am, vs) %>%
        sample_n(3)

        foo <- function(model, am, mpg){
        print(
        paste("The", model, "has a", am, "transmission and gets", mpg, "mpgs.")
        )
        }

        ds_mt %>%
        select(model, am, mpg) %>%
        pwalk(
        .l = .,
        .f = foo
        )





        share|improve this answer













        So after some more reading it seems this is a case for pwalk() rather than pmap(), because I am trying to get output to print (i.e., a side effect) rather than to be stored in a dataframe.



        library(dplyr)
        library(purrr)
        library(tibble)

        set.seed(57)

        ds_mt <-
        mtcars %>%
        rownames_to_column("model") %>%
        mutate(
        am = factor(am, labels = c("auto", "manual")),
        vs = factor(vs, labels = c("V", "S"))
        ) %>%
        select(model, mpg, wt, cyl, am, vs) %>%
        sample_n(3)

        foo <- function(model, am, mpg){
        print(
        paste("The", model, "has a", am, "transmission and gets", mpg, "mpgs.")
        )
        }

        ds_mt %>%
        select(model, am, mpg) %>%
        pwalk(
        .l = .,
        .f = foo
        )






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 27 '18 at 0:22









        JoeJoe

        733615




        733615
































            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53403156%2fusing-purrrpmap-in-a-rowwise-manner-outside-of-mutate%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            這個網誌中的熱門文章

            Xamarin.form Move up view when keyboard appear

            Post-Redirect-Get with Spring WebFlux and Thymeleaf

            Anylogic : not able to use stopDelay()