mutate two or more columns if case_when is used





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







1















I am trying to use the case_when function for a bunch of columns y a data.frame.



This case does not return the specified columns in mutate



cars %>% mutate (
km = speed * dist,
mt = km / 1000
) %>%
mutate (
.funs = case_when(
(speed < 20 ) ~ {
km = km * 2
mt = mt * 3
}
)
)


Thanks










share|improve this question































    1















    I am trying to use the case_when function for a bunch of columns y a data.frame.



    This case does not return the specified columns in mutate



    cars %>% mutate (
    km = speed * dist,
    mt = km / 1000
    ) %>%
    mutate (
    .funs = case_when(
    (speed < 20 ) ~ {
    km = km * 2
    mt = mt * 3
    }
    )
    )


    Thanks










    share|improve this question



























      1












      1








      1








      I am trying to use the case_when function for a bunch of columns y a data.frame.



      This case does not return the specified columns in mutate



      cars %>% mutate (
      km = speed * dist,
      mt = km / 1000
      ) %>%
      mutate (
      .funs = case_when(
      (speed < 20 ) ~ {
      km = km * 2
      mt = mt * 3
      }
      )
      )


      Thanks










      share|improve this question
















      I am trying to use the case_when function for a bunch of columns y a data.frame.



      This case does not return the specified columns in mutate



      cars %>% mutate (
      km = speed * dist,
      mt = km / 1000
      ) %>%
      mutate (
      .funs = case_when(
      (speed < 20 ) ~ {
      km = km * 2
      mt = mt * 3
      }
      )
      )


      Thanks







      r dplyr






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 16 '18 at 19:57







      Captain Tyler

















      asked Nov 16 '18 at 19:46









      Captain TylerCaptain Tyler

      12213




      12213
























          2 Answers
          2






          active

          oldest

          votes


















          2














          We could use mutate_at



          library(tidyverse)
          cars %>%
          mutate(km = speed * dist, mt = km/1000) %>%
          mutate_at(vars(km, mt), funs(case_when(speed < 20 ~ .*2,
          TRUE ~ .)))




          If we need to do computation with separate values for each of the column, then use map2 or pmap



          out <- cars %>%
          mutate(km = speed * dist, mt = km/1000) %>%
          select(km, mt) %>%
          map2_df(., list(2, 3), ~
          case_when(cars$speed < 20 ~ .x * .y, TRUE ~ .x)) %>%
          bind_cols(cars, .)

          head(out)
          # speed dist km mt
          #1 4 2 16 0.024
          #2 4 10 80 0.120
          #3 7 4 56 0.084
          #4 7 22 308 0.462
          #5 8 16 256 0.384
          #6 9 10 180 0.270





          share|improve this answer


























          • I ve edit the example. The mutated vars are now km = km * 2 and mt = mt * 3

            – Captain Tyler
            Nov 16 '18 at 19:59











          • @CaptainTyler Is there any other conditions?

            – akrun
            Nov 16 '18 at 20:13











          • The objetive is mutate more than a column (existing or new) based in some row conditions

            – Captain Tyler
            Nov 16 '18 at 20:15











          • @CaptainTyler Thanks, Updated the solution

            – akrun
            Nov 16 '18 at 20:27





















          1














          Discover this solution, but is a bit weird and tricky



          mutate_when <- function (data, ...) {
          dots <- eval (substitute (alist(...)))
          for (i in seq (1, length (dots), by = 3)) {
          condition <- eval (dots [[i]], envir = data)
          mutations <- eval (dots [[i + 1]], envir = data [condition, ])
          data[condition, names(mutations)] <- mutations
          mutations_else <- eval (dots [[i + 2]], envir = data [!condition, ])
          data[!condition, names(mutations)] <- mutations_else
          }
          data
          }

          cars %>%
          mutate(
          km = speed * dist,
          mt = km/1000
          ) %>%
          mutate_when(
          speed < 20,
          list (
          km = km * 2,
          mt = mt * 3
          ),
          list (
          0
          )
          )


          Gives



             speed dist   km    mt
          1 4 2 16 0.024
          2 4 10 80 0.120
          3 7 4 56 0.084
          4 7 22 308 0.462
          5 8 16 256 0.384
          6 9 10 180 0.270





          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%2f53344411%2fmutate-two-or-more-columns-if-case-when-is-used%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            2














            We could use mutate_at



            library(tidyverse)
            cars %>%
            mutate(km = speed * dist, mt = km/1000) %>%
            mutate_at(vars(km, mt), funs(case_when(speed < 20 ~ .*2,
            TRUE ~ .)))




            If we need to do computation with separate values for each of the column, then use map2 or pmap



            out <- cars %>%
            mutate(km = speed * dist, mt = km/1000) %>%
            select(km, mt) %>%
            map2_df(., list(2, 3), ~
            case_when(cars$speed < 20 ~ .x * .y, TRUE ~ .x)) %>%
            bind_cols(cars, .)

            head(out)
            # speed dist km mt
            #1 4 2 16 0.024
            #2 4 10 80 0.120
            #3 7 4 56 0.084
            #4 7 22 308 0.462
            #5 8 16 256 0.384
            #6 9 10 180 0.270





            share|improve this answer


























            • I ve edit the example. The mutated vars are now km = km * 2 and mt = mt * 3

              – Captain Tyler
              Nov 16 '18 at 19:59











            • @CaptainTyler Is there any other conditions?

              – akrun
              Nov 16 '18 at 20:13











            • The objetive is mutate more than a column (existing or new) based in some row conditions

              – Captain Tyler
              Nov 16 '18 at 20:15











            • @CaptainTyler Thanks, Updated the solution

              – akrun
              Nov 16 '18 at 20:27


















            2














            We could use mutate_at



            library(tidyverse)
            cars %>%
            mutate(km = speed * dist, mt = km/1000) %>%
            mutate_at(vars(km, mt), funs(case_when(speed < 20 ~ .*2,
            TRUE ~ .)))




            If we need to do computation with separate values for each of the column, then use map2 or pmap



            out <- cars %>%
            mutate(km = speed * dist, mt = km/1000) %>%
            select(km, mt) %>%
            map2_df(., list(2, 3), ~
            case_when(cars$speed < 20 ~ .x * .y, TRUE ~ .x)) %>%
            bind_cols(cars, .)

            head(out)
            # speed dist km mt
            #1 4 2 16 0.024
            #2 4 10 80 0.120
            #3 7 4 56 0.084
            #4 7 22 308 0.462
            #5 8 16 256 0.384
            #6 9 10 180 0.270





            share|improve this answer


























            • I ve edit the example. The mutated vars are now km = km * 2 and mt = mt * 3

              – Captain Tyler
              Nov 16 '18 at 19:59











            • @CaptainTyler Is there any other conditions?

              – akrun
              Nov 16 '18 at 20:13











            • The objetive is mutate more than a column (existing or new) based in some row conditions

              – Captain Tyler
              Nov 16 '18 at 20:15











            • @CaptainTyler Thanks, Updated the solution

              – akrun
              Nov 16 '18 at 20:27
















            2












            2








            2







            We could use mutate_at



            library(tidyverse)
            cars %>%
            mutate(km = speed * dist, mt = km/1000) %>%
            mutate_at(vars(km, mt), funs(case_when(speed < 20 ~ .*2,
            TRUE ~ .)))




            If we need to do computation with separate values for each of the column, then use map2 or pmap



            out <- cars %>%
            mutate(km = speed * dist, mt = km/1000) %>%
            select(km, mt) %>%
            map2_df(., list(2, 3), ~
            case_when(cars$speed < 20 ~ .x * .y, TRUE ~ .x)) %>%
            bind_cols(cars, .)

            head(out)
            # speed dist km mt
            #1 4 2 16 0.024
            #2 4 10 80 0.120
            #3 7 4 56 0.084
            #4 7 22 308 0.462
            #5 8 16 256 0.384
            #6 9 10 180 0.270





            share|improve this answer















            We could use mutate_at



            library(tidyverse)
            cars %>%
            mutate(km = speed * dist, mt = km/1000) %>%
            mutate_at(vars(km, mt), funs(case_when(speed < 20 ~ .*2,
            TRUE ~ .)))




            If we need to do computation with separate values for each of the column, then use map2 or pmap



            out <- cars %>%
            mutate(km = speed * dist, mt = km/1000) %>%
            select(km, mt) %>%
            map2_df(., list(2, 3), ~
            case_when(cars$speed < 20 ~ .x * .y, TRUE ~ .x)) %>%
            bind_cols(cars, .)

            head(out)
            # speed dist km mt
            #1 4 2 16 0.024
            #2 4 10 80 0.120
            #3 7 4 56 0.084
            #4 7 22 308 0.462
            #5 8 16 256 0.384
            #6 9 10 180 0.270






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 16 '18 at 20:20

























            answered Nov 16 '18 at 19:49









            akrunakrun

            422k13209285




            422k13209285













            • I ve edit the example. The mutated vars are now km = km * 2 and mt = mt * 3

              – Captain Tyler
              Nov 16 '18 at 19:59











            • @CaptainTyler Is there any other conditions?

              – akrun
              Nov 16 '18 at 20:13











            • The objetive is mutate more than a column (existing or new) based in some row conditions

              – Captain Tyler
              Nov 16 '18 at 20:15











            • @CaptainTyler Thanks, Updated the solution

              – akrun
              Nov 16 '18 at 20:27





















            • I ve edit the example. The mutated vars are now km = km * 2 and mt = mt * 3

              – Captain Tyler
              Nov 16 '18 at 19:59











            • @CaptainTyler Is there any other conditions?

              – akrun
              Nov 16 '18 at 20:13











            • The objetive is mutate more than a column (existing or new) based in some row conditions

              – Captain Tyler
              Nov 16 '18 at 20:15











            • @CaptainTyler Thanks, Updated the solution

              – akrun
              Nov 16 '18 at 20:27



















            I ve edit the example. The mutated vars are now km = km * 2 and mt = mt * 3

            – Captain Tyler
            Nov 16 '18 at 19:59





            I ve edit the example. The mutated vars are now km = km * 2 and mt = mt * 3

            – Captain Tyler
            Nov 16 '18 at 19:59













            @CaptainTyler Is there any other conditions?

            – akrun
            Nov 16 '18 at 20:13





            @CaptainTyler Is there any other conditions?

            – akrun
            Nov 16 '18 at 20:13













            The objetive is mutate more than a column (existing or new) based in some row conditions

            – Captain Tyler
            Nov 16 '18 at 20:15





            The objetive is mutate more than a column (existing or new) based in some row conditions

            – Captain Tyler
            Nov 16 '18 at 20:15













            @CaptainTyler Thanks, Updated the solution

            – akrun
            Nov 16 '18 at 20:27







            @CaptainTyler Thanks, Updated the solution

            – akrun
            Nov 16 '18 at 20:27















            1














            Discover this solution, but is a bit weird and tricky



            mutate_when <- function (data, ...) {
            dots <- eval (substitute (alist(...)))
            for (i in seq (1, length (dots), by = 3)) {
            condition <- eval (dots [[i]], envir = data)
            mutations <- eval (dots [[i + 1]], envir = data [condition, ])
            data[condition, names(mutations)] <- mutations
            mutations_else <- eval (dots [[i + 2]], envir = data [!condition, ])
            data[!condition, names(mutations)] <- mutations_else
            }
            data
            }

            cars %>%
            mutate(
            km = speed * dist,
            mt = km/1000
            ) %>%
            mutate_when(
            speed < 20,
            list (
            km = km * 2,
            mt = mt * 3
            ),
            list (
            0
            )
            )


            Gives



               speed dist   km    mt
            1 4 2 16 0.024
            2 4 10 80 0.120
            3 7 4 56 0.084
            4 7 22 308 0.462
            5 8 16 256 0.384
            6 9 10 180 0.270





            share|improve this answer




























              1














              Discover this solution, but is a bit weird and tricky



              mutate_when <- function (data, ...) {
              dots <- eval (substitute (alist(...)))
              for (i in seq (1, length (dots), by = 3)) {
              condition <- eval (dots [[i]], envir = data)
              mutations <- eval (dots [[i + 1]], envir = data [condition, ])
              data[condition, names(mutations)] <- mutations
              mutations_else <- eval (dots [[i + 2]], envir = data [!condition, ])
              data[!condition, names(mutations)] <- mutations_else
              }
              data
              }

              cars %>%
              mutate(
              km = speed * dist,
              mt = km/1000
              ) %>%
              mutate_when(
              speed < 20,
              list (
              km = km * 2,
              mt = mt * 3
              ),
              list (
              0
              )
              )


              Gives



                 speed dist   km    mt
              1 4 2 16 0.024
              2 4 10 80 0.120
              3 7 4 56 0.084
              4 7 22 308 0.462
              5 8 16 256 0.384
              6 9 10 180 0.270





              share|improve this answer


























                1












                1








                1







                Discover this solution, but is a bit weird and tricky



                mutate_when <- function (data, ...) {
                dots <- eval (substitute (alist(...)))
                for (i in seq (1, length (dots), by = 3)) {
                condition <- eval (dots [[i]], envir = data)
                mutations <- eval (dots [[i + 1]], envir = data [condition, ])
                data[condition, names(mutations)] <- mutations
                mutations_else <- eval (dots [[i + 2]], envir = data [!condition, ])
                data[!condition, names(mutations)] <- mutations_else
                }
                data
                }

                cars %>%
                mutate(
                km = speed * dist,
                mt = km/1000
                ) %>%
                mutate_when(
                speed < 20,
                list (
                km = km * 2,
                mt = mt * 3
                ),
                list (
                0
                )
                )


                Gives



                   speed dist   km    mt
                1 4 2 16 0.024
                2 4 10 80 0.120
                3 7 4 56 0.084
                4 7 22 308 0.462
                5 8 16 256 0.384
                6 9 10 180 0.270





                share|improve this answer













                Discover this solution, but is a bit weird and tricky



                mutate_when <- function (data, ...) {
                dots <- eval (substitute (alist(...)))
                for (i in seq (1, length (dots), by = 3)) {
                condition <- eval (dots [[i]], envir = data)
                mutations <- eval (dots [[i + 1]], envir = data [condition, ])
                data[condition, names(mutations)] <- mutations
                mutations_else <- eval (dots [[i + 2]], envir = data [!condition, ])
                data[!condition, names(mutations)] <- mutations_else
                }
                data
                }

                cars %>%
                mutate(
                km = speed * dist,
                mt = km/1000
                ) %>%
                mutate_when(
                speed < 20,
                list (
                km = km * 2,
                mt = mt * 3
                ),
                list (
                0
                )
                )


                Gives



                   speed dist   km    mt
                1 4 2 16 0.024
                2 4 10 80 0.120
                3 7 4 56 0.084
                4 7 22 308 0.462
                5 8 16 256 0.384
                6 9 10 180 0.270






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 16 '18 at 20:14









                Captain TylerCaptain Tyler

                12213




                12213






























                    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%2f53344411%2fmutate-two-or-more-columns-if-case-when-is-used%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







                    Popular posts from this blog

                    Bressuire

                    Vorschmack

                    Quarantine