Mutate with dynamic column names dplyr2019 Community Moderator ElectionWhich packages or functions can I use in R to plot 3D data like this?How to replace NA values with another value in factors in R?Nested features with one to many relationshipsCombining results via arithmetic meanMeaning of “TRUE” column in R RandomForest output for Importance()?Binary classification to predict various targets250 Categorical valuesMutate with custom function in R does not work

What is the intuition behind short exact sequences of groups; in particular, what is the intuition behind group extensions?

How to show the equivalence between the regularized regression and their constraint formulas using KKT

How could indestructible materials be used in power generation?

How do conventional missiles fly?

Twin primes whose sum is a cube

Is it unprofessional to ask if a job posting on GlassDoor is real?

Neighboring nodes in the network

Can a virus destroy the BIOS of a modern computer?

Anagram holiday

What killed these X2 caps?

90's TV series where a boy goes to another dimension through portal near power lines

Fully-Firstable Anagram Sets

Withdrawals from HSA

How can I prevent hyper evolved versions of regular creatures from wiping out their cousins?

Doing something right before you need it - expression for this?

Etiquette around loan refinance - decision is going to cost first broker a lot of money

Increase size of symbol intercal when in superscript position

Should I tell management that I intend to leave due to bad software development practices?

Why does Arabsat 6A need a Falcon Heavy to launch

Western buddy movie with a supernatural twist where a woman turns into an eagle at the end

What's the point of deactivating Num Lock on login screens?

Could gravitational lensing be used to protect a spaceship from a laser?

Alternative to sending password over mail?

What exploit are these user agents trying to use?



Mutate with dynamic column names dplyr



2019 Community Moderator ElectionWhich packages or functions can I use in R to plot 3D data like this?How to replace NA values with another value in factors in R?Nested features with one to many relationshipsCombining results via arithmetic meanMeaning of “TRUE” column in R RandomForest output for Importance()?Binary classification to predict various targets250 Categorical valuesMutate with custom function in R does not work










1












$begingroup$


Hi I have this dataset (It has many more columns)



 media brand radio tv cinema 
<chr> <dbl> <dbl> <dbl> <dbl>
radio 0 0 0 0
tv 0 0 0 0
cinema 0 0 0 0
tv 0 0 0 0
radio 0 0 0 0
tv 0 0 0 0


I want to obtain the following(Assign a 1 to each column based on the value of media column):



 media brand radio tv cinema 
<chr> <dbl> <dbl> <dbl> <dbl>
radio 0 1 0 0
tv 0 0 1 0
cinema 0 0 0 1
tv 0 0 1 0
radio 0 1 0 0
tv 0 0 1 0


Do you have any idea on how to do it?As I have many more columns, I'm trying to find a solution using dynamic variable assignment.
Thanks










share|improve this question









$endgroup$




bumped to the homepage by Community 5 hours ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.



















    1












    $begingroup$


    Hi I have this dataset (It has many more columns)



     media brand radio tv cinema 
    <chr> <dbl> <dbl> <dbl> <dbl>
    radio 0 0 0 0
    tv 0 0 0 0
    cinema 0 0 0 0
    tv 0 0 0 0
    radio 0 0 0 0
    tv 0 0 0 0


    I want to obtain the following(Assign a 1 to each column based on the value of media column):



     media brand radio tv cinema 
    <chr> <dbl> <dbl> <dbl> <dbl>
    radio 0 1 0 0
    tv 0 0 1 0
    cinema 0 0 0 1
    tv 0 0 1 0
    radio 0 1 0 0
    tv 0 0 1 0


    Do you have any idea on how to do it?As I have many more columns, I'm trying to find a solution using dynamic variable assignment.
    Thanks










    share|improve this question









    $endgroup$




    bumped to the homepage by Community 5 hours ago


    This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.

















      1












      1








      1





      $begingroup$


      Hi I have this dataset (It has many more columns)



       media brand radio tv cinema 
      <chr> <dbl> <dbl> <dbl> <dbl>
      radio 0 0 0 0
      tv 0 0 0 0
      cinema 0 0 0 0
      tv 0 0 0 0
      radio 0 0 0 0
      tv 0 0 0 0


      I want to obtain the following(Assign a 1 to each column based on the value of media column):



       media brand radio tv cinema 
      <chr> <dbl> <dbl> <dbl> <dbl>
      radio 0 1 0 0
      tv 0 0 1 0
      cinema 0 0 0 1
      tv 0 0 1 0
      radio 0 1 0 0
      tv 0 0 1 0


      Do you have any idea on how to do it?As I have many more columns, I'm trying to find a solution using dynamic variable assignment.
      Thanks










      share|improve this question









      $endgroup$




      Hi I have this dataset (It has many more columns)



       media brand radio tv cinema 
      <chr> <dbl> <dbl> <dbl> <dbl>
      radio 0 0 0 0
      tv 0 0 0 0
      cinema 0 0 0 0
      tv 0 0 0 0
      radio 0 0 0 0
      tv 0 0 0 0


      I want to obtain the following(Assign a 1 to each column based on the value of media column):



       media brand radio tv cinema 
      <chr> <dbl> <dbl> <dbl> <dbl>
      radio 0 1 0 0
      tv 0 0 1 0
      cinema 0 0 0 1
      tv 0 0 1 0
      radio 0 1 0 0
      tv 0 0 1 0


      Do you have any idea on how to do it?As I have many more columns, I'm trying to find a solution using dynamic variable assignment.
      Thanks







      machine-learning r preprocessing dplyr






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 5 at 9:05









      3nomis3nomis

      30611




      30611





      bumped to the homepage by Community 5 hours ago


      This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.







      bumped to the homepage by Community 5 hours ago


      This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.






















          1 Answer
          1






          active

          oldest

          votes


















          0












          $begingroup$

          What you are trying to do is called one hot encoding or dummy encoding. Even as this may be possible to accomplish in dplyr (together with tidyr), I would recommend using the function one_hot() from the library mltools. For an explanation, see the following code snippets:



          # set up sample data
          df <- data.frame(
          id = 1:4,
          media = factor(c("radio", NA, "tv", "tv"), levels=c("radio", "tv", "cinema"))
          )


          One Hot Encoding with tidyr:



          The following code snippet shows how you would accomplish one hot encoding with dplyr and tidyr (copied from this comment):



          library(dplyr)
          library(tidyr)

          tib <- as_tibble(df)
          tib %>%
          mutate(i = 1) %>%
          spread(media, i, fill = 0)


          However, this code will give you the following table:



          # A tibble: 4 x 4
          id radio tv `<NA>`
          <int> <dbl> <dbl> <dbl>
          1 1 0 0
          2 0 0 1
          3 0 1 0
          4 0 1 0


          Note that there is no cinema column present, even though we defined a respective level in our sample data-frame. Also, the spread()-function created an own column for values with NA's, treating them as a separate category.



          One Hot Encoding with mltools (recommended):



          library(data.table)
          library(mltools)

          dt <- data.table(df)
          one_hot(dt)


          This code will give you the following table:



          id color_radio color_tv color_cinema
          1 1 0 0
          2 NA NA NA
          3 0 1 0
          4 0 1 0


          As you can see, the column cinema is now present even though our sample data-frame did not contain any observations of it. Also, there isn't an NA-column present anymore. The NA from the second row is instead visible in all columns (which makes way more sense, since you don't know, what category this observation IS, so you cannot know what category it IS NOT).



          In addition, this code is not only easier to understand it also runs about two to three times as fast.






          share|improve this answer









          $endgroup$













            Your Answer





            StackExchange.ifUsing("editor", function ()
            return StackExchange.using("mathjaxEditing", function ()
            StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
            StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["$", "$"], ["\\(","\\)"]]);
            );
            );
            , "mathjax-editing");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "557"
            ;
            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: false,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: null,
            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%2fdatascience.stackexchange.com%2fquestions%2f46693%2fmutate-with-dynamic-column-names-dplyr%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












            $begingroup$

            What you are trying to do is called one hot encoding or dummy encoding. Even as this may be possible to accomplish in dplyr (together with tidyr), I would recommend using the function one_hot() from the library mltools. For an explanation, see the following code snippets:



            # set up sample data
            df <- data.frame(
            id = 1:4,
            media = factor(c("radio", NA, "tv", "tv"), levels=c("radio", "tv", "cinema"))
            )


            One Hot Encoding with tidyr:



            The following code snippet shows how you would accomplish one hot encoding with dplyr and tidyr (copied from this comment):



            library(dplyr)
            library(tidyr)

            tib <- as_tibble(df)
            tib %>%
            mutate(i = 1) %>%
            spread(media, i, fill = 0)


            However, this code will give you the following table:



            # A tibble: 4 x 4
            id radio tv `<NA>`
            <int> <dbl> <dbl> <dbl>
            1 1 0 0
            2 0 0 1
            3 0 1 0
            4 0 1 0


            Note that there is no cinema column present, even though we defined a respective level in our sample data-frame. Also, the spread()-function created an own column for values with NA's, treating them as a separate category.



            One Hot Encoding with mltools (recommended):



            library(data.table)
            library(mltools)

            dt <- data.table(df)
            one_hot(dt)


            This code will give you the following table:



            id color_radio color_tv color_cinema
            1 1 0 0
            2 NA NA NA
            3 0 1 0
            4 0 1 0


            As you can see, the column cinema is now present even though our sample data-frame did not contain any observations of it. Also, there isn't an NA-column present anymore. The NA from the second row is instead visible in all columns (which makes way more sense, since you don't know, what category this observation IS, so you cannot know what category it IS NOT).



            In addition, this code is not only easier to understand it also runs about two to three times as fast.






            share|improve this answer









            $endgroup$

















              0












              $begingroup$

              What you are trying to do is called one hot encoding or dummy encoding. Even as this may be possible to accomplish in dplyr (together with tidyr), I would recommend using the function one_hot() from the library mltools. For an explanation, see the following code snippets:



              # set up sample data
              df <- data.frame(
              id = 1:4,
              media = factor(c("radio", NA, "tv", "tv"), levels=c("radio", "tv", "cinema"))
              )


              One Hot Encoding with tidyr:



              The following code snippet shows how you would accomplish one hot encoding with dplyr and tidyr (copied from this comment):



              library(dplyr)
              library(tidyr)

              tib <- as_tibble(df)
              tib %>%
              mutate(i = 1) %>%
              spread(media, i, fill = 0)


              However, this code will give you the following table:



              # A tibble: 4 x 4
              id radio tv `<NA>`
              <int> <dbl> <dbl> <dbl>
              1 1 0 0
              2 0 0 1
              3 0 1 0
              4 0 1 0


              Note that there is no cinema column present, even though we defined a respective level in our sample data-frame. Also, the spread()-function created an own column for values with NA's, treating them as a separate category.



              One Hot Encoding with mltools (recommended):



              library(data.table)
              library(mltools)

              dt <- data.table(df)
              one_hot(dt)


              This code will give you the following table:



              id color_radio color_tv color_cinema
              1 1 0 0
              2 NA NA NA
              3 0 1 0
              4 0 1 0


              As you can see, the column cinema is now present even though our sample data-frame did not contain any observations of it. Also, there isn't an NA-column present anymore. The NA from the second row is instead visible in all columns (which makes way more sense, since you don't know, what category this observation IS, so you cannot know what category it IS NOT).



              In addition, this code is not only easier to understand it also runs about two to three times as fast.






              share|improve this answer









              $endgroup$















                0












                0








                0





                $begingroup$

                What you are trying to do is called one hot encoding or dummy encoding. Even as this may be possible to accomplish in dplyr (together with tidyr), I would recommend using the function one_hot() from the library mltools. For an explanation, see the following code snippets:



                # set up sample data
                df <- data.frame(
                id = 1:4,
                media = factor(c("radio", NA, "tv", "tv"), levels=c("radio", "tv", "cinema"))
                )


                One Hot Encoding with tidyr:



                The following code snippet shows how you would accomplish one hot encoding with dplyr and tidyr (copied from this comment):



                library(dplyr)
                library(tidyr)

                tib <- as_tibble(df)
                tib %>%
                mutate(i = 1) %>%
                spread(media, i, fill = 0)


                However, this code will give you the following table:



                # A tibble: 4 x 4
                id radio tv `<NA>`
                <int> <dbl> <dbl> <dbl>
                1 1 0 0
                2 0 0 1
                3 0 1 0
                4 0 1 0


                Note that there is no cinema column present, even though we defined a respective level in our sample data-frame. Also, the spread()-function created an own column for values with NA's, treating them as a separate category.



                One Hot Encoding with mltools (recommended):



                library(data.table)
                library(mltools)

                dt <- data.table(df)
                one_hot(dt)


                This code will give you the following table:



                id color_radio color_tv color_cinema
                1 1 0 0
                2 NA NA NA
                3 0 1 0
                4 0 1 0


                As you can see, the column cinema is now present even though our sample data-frame did not contain any observations of it. Also, there isn't an NA-column present anymore. The NA from the second row is instead visible in all columns (which makes way more sense, since you don't know, what category this observation IS, so you cannot know what category it IS NOT).



                In addition, this code is not only easier to understand it also runs about two to three times as fast.






                share|improve this answer









                $endgroup$



                What you are trying to do is called one hot encoding or dummy encoding. Even as this may be possible to accomplish in dplyr (together with tidyr), I would recommend using the function one_hot() from the library mltools. For an explanation, see the following code snippets:



                # set up sample data
                df <- data.frame(
                id = 1:4,
                media = factor(c("radio", NA, "tv", "tv"), levels=c("radio", "tv", "cinema"))
                )


                One Hot Encoding with tidyr:



                The following code snippet shows how you would accomplish one hot encoding with dplyr and tidyr (copied from this comment):



                library(dplyr)
                library(tidyr)

                tib <- as_tibble(df)
                tib %>%
                mutate(i = 1) %>%
                spread(media, i, fill = 0)


                However, this code will give you the following table:



                # A tibble: 4 x 4
                id radio tv `<NA>`
                <int> <dbl> <dbl> <dbl>
                1 1 0 0
                2 0 0 1
                3 0 1 0
                4 0 1 0


                Note that there is no cinema column present, even though we defined a respective level in our sample data-frame. Also, the spread()-function created an own column for values with NA's, treating them as a separate category.



                One Hot Encoding with mltools (recommended):



                library(data.table)
                library(mltools)

                dt <- data.table(df)
                one_hot(dt)


                This code will give you the following table:



                id color_radio color_tv color_cinema
                1 1 0 0
                2 NA NA NA
                3 0 1 0
                4 0 1 0


                As you can see, the column cinema is now present even though our sample data-frame did not contain any observations of it. Also, there isn't an NA-column present anymore. The NA from the second row is instead visible in all columns (which makes way more sense, since you don't know, what category this observation IS, so you cannot know what category it IS NOT).



                In addition, this code is not only easier to understand it also runs about two to three times as fast.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Mar 5 at 16:36









                georg_ungeorg_un

                586




                586



























                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Data Science Stack Exchange!


                    • 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.

                    Use MathJax to format equations. MathJax reference.


                    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%2fdatascience.stackexchange.com%2fquestions%2f46693%2fmutate-with-dynamic-column-names-dplyr%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

                    Ружовы пелікан Змест Знешні выгляд | Пашырэнне | Асаблівасці біялогіі | Літаратура | НавігацыяДагледжаная версіяправерана1 зменаДагледжаная версіяправерана1 змена/ 22697590 Сістэматыкана ВіківідахВыявына Вікісховішчы174693363011049382

                    ValueError: Error when checking input: expected conv2d_13_input to have shape (3, 150, 150) but got array with shape (150, 150, 3)2019 Community Moderator ElectionError when checking : expected dense_1_input to have shape (None, 5) but got array with shape (200, 1)Error 'Expected 2D array, got 1D array instead:'ValueError: Error when checking input: expected lstm_41_input to have 3 dimensions, but got array with shape (40000,100)ValueError: Error when checking target: expected dense_1 to have shape (7,) but got array with shape (1,)ValueError: Error when checking target: expected dense_2 to have shape (1,) but got array with shape (0,)Keras exception: ValueError: Error when checking input: expected conv2d_1_input to have shape (150, 150, 3) but got array with shape (256, 256, 3)Steps taking too long to completewhen checking input: expected dense_1_input to have shape (13328,) but got array with shape (317,)ValueError: Error when checking target: expected dense_3 to have shape (None, 1) but got array with shape (7715, 40000)Keras exception: Error when checking input: expected dense_input to have shape (2,) but got array with shape (1,)

                    Illegal assignment from SObject to ContactFetching String, Id from Map - Illegal Assignment Id to Field / ObjectError: Compile Error: Illegal assignment from String to BooleanError: List has no rows for assignment to SObjectError on Test Class - System.QueryException: List has no rows for assignment to SObjectRemote action problemDML requires SObject or SObject list type error“Illegal assignment from List to List”Test Class Fail: Batch Class: System.QueryException: List has no rows for assignment to SObjectMapping to a user'List has no rows for assignment to SObject' Mystery