add a label in a new column according to string match in Rdplyr mutate in R - add column as concat of columnsFiltering row which contains a certain string using dplyruse dplyr to select columnsFaster alternative to extract all words in text matching words in another vectorCompare data frame with vector and create new variable for matched valueDetect a list of words in a string variable and extract matched words to a new variable in data frameRemove multiple matching columns from multiple character stringExtract certain characters from list and convert them into a character vectorUse stringr to extract multiple character strings from large databaseConditional String Match R Character Vector Collapse Select Elements

What happens if you roll doubles 3 times then land on "Go to jail?"

I'm in charge of equipment buying but no one's ever happy with what I choose. How to fix this?

Customer Requests (Sometimes) Drive Me Bonkers!

Trouble understanding the speech of overseas colleagues

How did Arya survive the stabbing?

Where does the Z80 processor start executing from?

Why escape if the_content isnt?

How to safely derail a train during transit?

How can I get through very long and very dry, but also very useful technical documents when learning a new tool?

What Brexit proposals are on the table in the indicative votes on the 27th of March 2019?

How did Doctor Strange see the winning outcome in Avengers: Infinity War?

How do we know the LHC results are robust?

Is expanding the research of a group into machine learning as a PhD student risky?

Hostile work environment after whistle-blowing on coworker and our boss. What do I do?

How to pronounce the slash sign

Tiptoe or tiphoof? Adjusting words to better fit fantasy races

Gears on left are inverse to gears on right?

Would this custom Sorcerer variant that can only learn any verbal-component-only spell be unbalanced?

Applicability of Single Responsibility Principle

Was Spock the First Vulcan in Starfleet?

Escape a backup date in a file name

Class Action - which options I have?

Avoiding estate tax by giving multiple gifts

Why are there no referendums in the US?



add a label in a new column according to string match in R


dplyr mutate in R - add column as concat of columnsFiltering row which contains a certain string using dplyruse dplyr to select columnsFaster alternative to extract all words in text matching words in another vectorCompare data frame with vector and create new variable for matched valueDetect a list of words in a string variable and extract matched words to a new variable in data frameRemove multiple matching columns from multiple character stringExtract certain characters from list and convert them into a character vectorUse stringr to extract multiple character strings from large databaseConditional String Match R Character Vector Collapse Select Elements













1















I did a string match with str_detect of stringr and filter data of my df according to them.



df



 variable x y z
AN B C D
EF F G H


The code is:



df_filtered <- df %>% filter(str_detect(variable, paste(dict, collapse="|")))


"dict" is my list of words (a character vector) that I want to detect in my data frame.



 dict
A
C
D
G


and i obtained:



 variable x y z
AN B C D


i want to add a new column for each row extracted, containing the element of dict that match.



 variable x y z dict
AN B C D A


how can I do?










share|improve this question




























    1















    I did a string match with str_detect of stringr and filter data of my df according to them.



    df



     variable x y z
    AN B C D
    EF F G H


    The code is:



    df_filtered <- df %>% filter(str_detect(variable, paste(dict, collapse="|")))


    "dict" is my list of words (a character vector) that I want to detect in my data frame.



     dict
    A
    C
    D
    G


    and i obtained:



     variable x y z
    AN B C D


    i want to add a new column for each row extracted, containing the element of dict that match.



     variable x y z dict
    AN B C D A


    how can I do?










    share|improve this question


























      1












      1








      1








      I did a string match with str_detect of stringr and filter data of my df according to them.



      df



       variable x y z
      AN B C D
      EF F G H


      The code is:



      df_filtered <- df %>% filter(str_detect(variable, paste(dict, collapse="|")))


      "dict" is my list of words (a character vector) that I want to detect in my data frame.



       dict
      A
      C
      D
      G


      and i obtained:



       variable x y z
      AN B C D


      i want to add a new column for each row extracted, containing the element of dict that match.



       variable x y z dict
      AN B C D A


      how can I do?










      share|improve this question
















      I did a string match with str_detect of stringr and filter data of my df according to them.



      df



       variable x y z
      AN B C D
      EF F G H


      The code is:



      df_filtered <- df %>% filter(str_detect(variable, paste(dict, collapse="|")))


      "dict" is my list of words (a character vector) that I want to detect in my data frame.



       dict
      A
      C
      D
      G


      and i obtained:



       variable x y z
      AN B C D


      i want to add a new column for each row extracted, containing the element of dict that match.



       variable x y z dict
      AN B C D A


      how can I do?







      r filter dplyr stringr






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 9 at 9:41









      JJJ

      69611221




      69611221










      asked Mar 8 at 11:17









      Silvia Silvia

      1598




      1598






















          1 Answer
          1






          active

          oldest

          votes


















          0














          In case that you can be sure that there is only one dict entry per line, the code is quite simple.



          library(tidyverse)
          dict <- c("a", "c", "d", "g")

          # I create a random dataframe
          (df <- tibble(variable = stringi::stri_rand_strings(1000, 3, pattern = "[a-z]")))
          # A tibble: 1,000 x 1
          variable
          <chr>
          1 tmx
          2 rgq
          3 pkm
          4 tue
          5 wet
          6 slx
          7 lkq
          8 std
          9 ivu
          10 vyt
          # ... with 990 more rows

          # I map your dict list to the dataframe
          (df_out <- map_df(dict, ~ filter(df, str_detect(variable, .x)) %>%
          mutate(out = str_extract(variable, .x))))
          # A tibble: 437 x 2
          variable out
          <chr> <chr>
          1 rar a
          2 cam a
          3 kba a
          4 wax a
          5 zta a
          6 aep a
          7 wao a
          8 bga a
          9 auv a
          10 bea a
          # ... with 427 more rows

          # Merge all dict-hits per entry
          (df_out <- df_out %>%
          nest(out, .key = "out") %>%
          mutate(out = map_chr(out, ~ str_c(.x$out, collapse = "_"))))
          # A tibble: 379 x 2
          variable out
          <chr> <chr>
          1 rar a
          2 cam a_c
          3 kba a
          4 wax a
          5 zta a
          6 aep a
          7 wao a
          8 bga a_g
          9 auv a
          10 bea a
          # ... with 369 more rows


          [solved by edit] If you run this code with more than one dict entry per line, the code will generate one line per dict hit.






          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%2f55062118%2fadd-a-label-in-a-new-column-according-to-string-match-in-r%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














            In case that you can be sure that there is only one dict entry per line, the code is quite simple.



            library(tidyverse)
            dict <- c("a", "c", "d", "g")

            # I create a random dataframe
            (df <- tibble(variable = stringi::stri_rand_strings(1000, 3, pattern = "[a-z]")))
            # A tibble: 1,000 x 1
            variable
            <chr>
            1 tmx
            2 rgq
            3 pkm
            4 tue
            5 wet
            6 slx
            7 lkq
            8 std
            9 ivu
            10 vyt
            # ... with 990 more rows

            # I map your dict list to the dataframe
            (df_out <- map_df(dict, ~ filter(df, str_detect(variable, .x)) %>%
            mutate(out = str_extract(variable, .x))))
            # A tibble: 437 x 2
            variable out
            <chr> <chr>
            1 rar a
            2 cam a
            3 kba a
            4 wax a
            5 zta a
            6 aep a
            7 wao a
            8 bga a
            9 auv a
            10 bea a
            # ... with 427 more rows

            # Merge all dict-hits per entry
            (df_out <- df_out %>%
            nest(out, .key = "out") %>%
            mutate(out = map_chr(out, ~ str_c(.x$out, collapse = "_"))))
            # A tibble: 379 x 2
            variable out
            <chr> <chr>
            1 rar a
            2 cam a_c
            3 kba a
            4 wax a
            5 zta a
            6 aep a
            7 wao a
            8 bga a_g
            9 auv a
            10 bea a
            # ... with 369 more rows


            [solved by edit] If you run this code with more than one dict entry per line, the code will generate one line per dict hit.






            share|improve this answer





























              0














              In case that you can be sure that there is only one dict entry per line, the code is quite simple.



              library(tidyverse)
              dict <- c("a", "c", "d", "g")

              # I create a random dataframe
              (df <- tibble(variable = stringi::stri_rand_strings(1000, 3, pattern = "[a-z]")))
              # A tibble: 1,000 x 1
              variable
              <chr>
              1 tmx
              2 rgq
              3 pkm
              4 tue
              5 wet
              6 slx
              7 lkq
              8 std
              9 ivu
              10 vyt
              # ... with 990 more rows

              # I map your dict list to the dataframe
              (df_out <- map_df(dict, ~ filter(df, str_detect(variable, .x)) %>%
              mutate(out = str_extract(variable, .x))))
              # A tibble: 437 x 2
              variable out
              <chr> <chr>
              1 rar a
              2 cam a
              3 kba a
              4 wax a
              5 zta a
              6 aep a
              7 wao a
              8 bga a
              9 auv a
              10 bea a
              # ... with 427 more rows

              # Merge all dict-hits per entry
              (df_out <- df_out %>%
              nest(out, .key = "out") %>%
              mutate(out = map_chr(out, ~ str_c(.x$out, collapse = "_"))))
              # A tibble: 379 x 2
              variable out
              <chr> <chr>
              1 rar a
              2 cam a_c
              3 kba a
              4 wax a
              5 zta a
              6 aep a
              7 wao a
              8 bga a_g
              9 auv a
              10 bea a
              # ... with 369 more rows


              [solved by edit] If you run this code with more than one dict entry per line, the code will generate one line per dict hit.






              share|improve this answer



























                0












                0








                0







                In case that you can be sure that there is only one dict entry per line, the code is quite simple.



                library(tidyverse)
                dict <- c("a", "c", "d", "g")

                # I create a random dataframe
                (df <- tibble(variable = stringi::stri_rand_strings(1000, 3, pattern = "[a-z]")))
                # A tibble: 1,000 x 1
                variable
                <chr>
                1 tmx
                2 rgq
                3 pkm
                4 tue
                5 wet
                6 slx
                7 lkq
                8 std
                9 ivu
                10 vyt
                # ... with 990 more rows

                # I map your dict list to the dataframe
                (df_out <- map_df(dict, ~ filter(df, str_detect(variable, .x)) %>%
                mutate(out = str_extract(variable, .x))))
                # A tibble: 437 x 2
                variable out
                <chr> <chr>
                1 rar a
                2 cam a
                3 kba a
                4 wax a
                5 zta a
                6 aep a
                7 wao a
                8 bga a
                9 auv a
                10 bea a
                # ... with 427 more rows

                # Merge all dict-hits per entry
                (df_out <- df_out %>%
                nest(out, .key = "out") %>%
                mutate(out = map_chr(out, ~ str_c(.x$out, collapse = "_"))))
                # A tibble: 379 x 2
                variable out
                <chr> <chr>
                1 rar a
                2 cam a_c
                3 kba a
                4 wax a
                5 zta a
                6 aep a
                7 wao a
                8 bga a_g
                9 auv a
                10 bea a
                # ... with 369 more rows


                [solved by edit] If you run this code with more than one dict entry per line, the code will generate one line per dict hit.






                share|improve this answer















                In case that you can be sure that there is only one dict entry per line, the code is quite simple.



                library(tidyverse)
                dict <- c("a", "c", "d", "g")

                # I create a random dataframe
                (df <- tibble(variable = stringi::stri_rand_strings(1000, 3, pattern = "[a-z]")))
                # A tibble: 1,000 x 1
                variable
                <chr>
                1 tmx
                2 rgq
                3 pkm
                4 tue
                5 wet
                6 slx
                7 lkq
                8 std
                9 ivu
                10 vyt
                # ... with 990 more rows

                # I map your dict list to the dataframe
                (df_out <- map_df(dict, ~ filter(df, str_detect(variable, .x)) %>%
                mutate(out = str_extract(variable, .x))))
                # A tibble: 437 x 2
                variable out
                <chr> <chr>
                1 rar a
                2 cam a
                3 kba a
                4 wax a
                5 zta a
                6 aep a
                7 wao a
                8 bga a
                9 auv a
                10 bea a
                # ... with 427 more rows

                # Merge all dict-hits per entry
                (df_out <- df_out %>%
                nest(out, .key = "out") %>%
                mutate(out = map_chr(out, ~ str_c(.x$out, collapse = "_"))))
                # A tibble: 379 x 2
                variable out
                <chr> <chr>
                1 rar a
                2 cam a_c
                3 kba a
                4 wax a
                5 zta a
                6 aep a
                7 wao a
                8 bga a_g
                9 auv a
                10 bea a
                # ... with 369 more rows


                [solved by edit] If you run this code with more than one dict entry per line, the code will generate one line per dict hit.







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Mar 8 at 18:27

























                answered Mar 8 at 13:59









                ha_puha_pu

                27219




                27219





























                    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%2f55062118%2fadd-a-label-in-a-new-column-according-to-string-match-in-r%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

                    Thal And Out Agency railway station See also References External links Navigation menuOfficial Web Site of Pakistan RailwaysArchivedOfficial Web Site of Pakistan Railwayseeexpanding ite

                    Understanding generators in Python2019 Community Moderator ElectionGenerator function not working pythonFor loop not executing two timesGenerators - Printing generated valuesWhy can a python generator only be used once?What exactly do generators do?What does the “yield” keyword do?What does “list comprehension” mean? How does it work and how can I use it?sklearn Kfold acces single fold instead of for loopIs a generator the callable? Which is the generator?Apply Border To Range Of Cells Using OpenpyxlCalling an external command in PythonWhat are metaclasses in Python?What is the difference between @staticmethod and @classmethod?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow can I safely create a nested directory in Python?Does Python have a ternary conditional operator?Understanding slice notationUnderstanding Python super() with __init__() methodsDoes Python have a string 'contains' substring method?

                    How can I change the color of pagination dots of UIPageControl?How to change UIPageControl dotsIs there a way to change page indicator dots colorCustomize dot with image of UIPageControl at index 0 of UIPageControlNo visible @interface for 'NSObject<PageControlDelegate>' declares the selector 'pageControlPageDidChange:'How to change the color of pagination dots in UIPageControl with a different color per pagepagecontrol indicator custom image instead of DefaultChanging the colour of UIPageControl dots in MonoTouchpagecontrol selectable page visibility color?Alternative way to load ViewControllers on a UIPageControlHow to set only layer.border-color for UIpage control dots in swiftHow can I develop for iPhone using a Windows development machine?How to change the name of an iOS app?UITableView - change section header coloruipagecontrol indicator(dot)issueCustom UIPageControl dots color not changingchange the interspace between UIPageControl dotsHow to change Status Bar text color in iOSHow can I change image tintColor in iOS and WatchKitUIPageControl dots with larger space in between each dotsHow to change the color of pagination dots in UIPageControl with a different color per page