How to write ifelse statement with multiple conditions in R?












1














I have a problem in writing ifelse statement ,I have three columns as shown below:



Team 1     Winner
T1 T1
T2 T1
T2 NA
T3 NA


I want another column : Result such that if Team=Winner it should be Winner else losser and If Team=anything & winner=NA then it should be no result...



Team 1     Winner   result
T1 T1 winner
T2 T1 losser
T2 NA noresult
T3 NA noresult


Any help would be appreciated.










share|improve this question





























    1














    I have a problem in writing ifelse statement ,I have three columns as shown below:



    Team 1     Winner
    T1 T1
    T2 T1
    T2 NA
    T3 NA


    I want another column : Result such that if Team=Winner it should be Winner else losser and If Team=anything & winner=NA then it should be no result...



    Team 1     Winner   result
    T1 T1 winner
    T2 T1 losser
    T2 NA noresult
    T3 NA noresult


    Any help would be appreciated.










    share|improve this question



























      1












      1








      1







      I have a problem in writing ifelse statement ,I have three columns as shown below:



      Team 1     Winner
      T1 T1
      T2 T1
      T2 NA
      T3 NA


      I want another column : Result such that if Team=Winner it should be Winner else losser and If Team=anything & winner=NA then it should be no result...



      Team 1     Winner   result
      T1 T1 winner
      T2 T1 losser
      T2 NA noresult
      T3 NA noresult


      Any help would be appreciated.










      share|improve this question















      I have a problem in writing ifelse statement ,I have three columns as shown below:



      Team 1     Winner
      T1 T1
      T2 T1
      T2 NA
      T3 NA


      I want another column : Result such that if Team=Winner it should be Winner else losser and If Team=anything & winner=NA then it should be no result...



      Team 1     Winner   result
      T1 T1 winner
      T2 T1 losser
      T2 NA noresult
      T3 NA noresult


      Any help would be appreciated.







      r






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 21 '18 at 8:31









      RLave

      3,5051922




      3,5051922










      asked Nov 21 '18 at 8:26









      Praveen Chougale

      817




      817
























          4 Answers
          4






          active

          oldest

          votes


















          1














          Use -



          df$Winner <- factor(df[,2], levels=unique(df$Team.1)) # avoid "level sets of factors are different" error
          df$result <- ifelse(df$Team.1 == df$Winner, "winner", "loser")
          df[is.na(df$result), "result"] <- "noresult"
          df


          Output



            Team.1 Winner   result
          1 T1 T1 winner
          2 T2 T1 loser
          3 T2 <NA> noresult
          4 T3 <NA> noresult





          share|improve this answer





























            2














            Another possibility is with case_when from dplyr:



            library(dplyr)

            df %>%
            mutate(Result = case_when(
            Team == Winner ~ "Winner",
            Team != Winner ~ "Loser",
            is.na(Winner) ~ "No result"
            ))


            # Team Winner Result
            # 1 T1 T1 Winner
            # 2 T2 T1 Loser
            # 3 T2 <NA> No result
            # 4 T3 <NA> No result


            Data:



            tt <- "Team     Winner
            T1 T1
            T2 T1
            T2 NA
            T3 NA"

            df <- read.table(text=tt, header = T, stringsAsFactors = F)





            share|improve this answer





























              2














              You can use dplyr::if_else(), as I learned, it is strict, because it checks the data type and it handles the NAs, making code simpler:



               df %>% mutate(Result = if_else( Team==Winner, "Winner", "Loser", missing ='No result'))
              Team Winner Result
              1 T1 T1 Winner
              2 T2 T1 Loser
              3 T2 <NA> No result
              4 T3 <NA> No result


              Despite, looking at the one-liner solution here, for your example data, it's not the fastest (the winner is the @Tim Biegeleisen 's answer, +1):



              Unit: microseconds
              expr min lq mean median uq max neval cld
              IF_ELSE 893.013 974.5060 1176.35331 1053.2260 1343.3590 2278.398 100 b
              IFELSE 20.481 34.3475 49.57934 47.3605 58.0275 143.361 100 a
              CASE 1067.946 1152.4255 1423.41426 1226.0255 1721.3850 4108.795 100 c


              So I can figure out a trade off between simplicity (that is subjective, of course) and more control (that is objective, due the nature of the functions), and velocity (if it's an issue to you, looking your real data, but it's more objective).






              share|improve this answer































                1














                Try this logic:



                df$result <- ifelse(is.na(df$Winner), "no result",
                ifelse(df$Team==df$Winner, "winner", "loser"))
                df

                Team Winner result
                1 T1 T1 winner
                2 T2 T1 loser
                3 T2 <NA> no result
                4 T3 <NA> no result





                share|improve this answer























                • This is give NA where I want it to be losser
                  – Praveen Chougale
                  Nov 21 '18 at 8:35










                • Answer updated.
                  – Tim Biegeleisen
                  Nov 21 '18 at 8:48











                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%2f53407875%2fhow-to-write-ifelse-statement-with-multiple-conditions-in-r%23new-answer', 'question_page');
                }
                );

                Post as a guest















                Required, but never shown

























                4 Answers
                4






                active

                oldest

                votes








                4 Answers
                4






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes









                1














                Use -



                df$Winner <- factor(df[,2], levels=unique(df$Team.1)) # avoid "level sets of factors are different" error
                df$result <- ifelse(df$Team.1 == df$Winner, "winner", "loser")
                df[is.na(df$result), "result"] <- "noresult"
                df


                Output



                  Team.1 Winner   result
                1 T1 T1 winner
                2 T2 T1 loser
                3 T2 <NA> noresult
                4 T3 <NA> noresult





                share|improve this answer


























                  1














                  Use -



                  df$Winner <- factor(df[,2], levels=unique(df$Team.1)) # avoid "level sets of factors are different" error
                  df$result <- ifelse(df$Team.1 == df$Winner, "winner", "loser")
                  df[is.na(df$result), "result"] <- "noresult"
                  df


                  Output



                    Team.1 Winner   result
                  1 T1 T1 winner
                  2 T2 T1 loser
                  3 T2 <NA> noresult
                  4 T3 <NA> noresult





                  share|improve this answer
























                    1












                    1








                    1






                    Use -



                    df$Winner <- factor(df[,2], levels=unique(df$Team.1)) # avoid "level sets of factors are different" error
                    df$result <- ifelse(df$Team.1 == df$Winner, "winner", "loser")
                    df[is.na(df$result), "result"] <- "noresult"
                    df


                    Output



                      Team.1 Winner   result
                    1 T1 T1 winner
                    2 T2 T1 loser
                    3 T2 <NA> noresult
                    4 T3 <NA> noresult





                    share|improve this answer












                    Use -



                    df$Winner <- factor(df[,2], levels=unique(df$Team.1)) # avoid "level sets of factors are different" error
                    df$result <- ifelse(df$Team.1 == df$Winner, "winner", "loser")
                    df[is.na(df$result), "result"] <- "noresult"
                    df


                    Output



                      Team.1 Winner   result
                    1 T1 T1 winner
                    2 T2 T1 loser
                    3 T2 <NA> noresult
                    4 T3 <NA> noresult






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 21 '18 at 8:37









                    Vivek Kalyanarangan

                    4,7761826




                    4,7761826

























                        2














                        Another possibility is with case_when from dplyr:



                        library(dplyr)

                        df %>%
                        mutate(Result = case_when(
                        Team == Winner ~ "Winner",
                        Team != Winner ~ "Loser",
                        is.na(Winner) ~ "No result"
                        ))


                        # Team Winner Result
                        # 1 T1 T1 Winner
                        # 2 T2 T1 Loser
                        # 3 T2 <NA> No result
                        # 4 T3 <NA> No result


                        Data:



                        tt <- "Team     Winner
                        T1 T1
                        T2 T1
                        T2 NA
                        T3 NA"

                        df <- read.table(text=tt, header = T, stringsAsFactors = F)





                        share|improve this answer


























                          2














                          Another possibility is with case_when from dplyr:



                          library(dplyr)

                          df %>%
                          mutate(Result = case_when(
                          Team == Winner ~ "Winner",
                          Team != Winner ~ "Loser",
                          is.na(Winner) ~ "No result"
                          ))


                          # Team Winner Result
                          # 1 T1 T1 Winner
                          # 2 T2 T1 Loser
                          # 3 T2 <NA> No result
                          # 4 T3 <NA> No result


                          Data:



                          tt <- "Team     Winner
                          T1 T1
                          T2 T1
                          T2 NA
                          T3 NA"

                          df <- read.table(text=tt, header = T, stringsAsFactors = F)





                          share|improve this answer
























                            2












                            2








                            2






                            Another possibility is with case_when from dplyr:



                            library(dplyr)

                            df %>%
                            mutate(Result = case_when(
                            Team == Winner ~ "Winner",
                            Team != Winner ~ "Loser",
                            is.na(Winner) ~ "No result"
                            ))


                            # Team Winner Result
                            # 1 T1 T1 Winner
                            # 2 T2 T1 Loser
                            # 3 T2 <NA> No result
                            # 4 T3 <NA> No result


                            Data:



                            tt <- "Team     Winner
                            T1 T1
                            T2 T1
                            T2 NA
                            T3 NA"

                            df <- read.table(text=tt, header = T, stringsAsFactors = F)





                            share|improve this answer












                            Another possibility is with case_when from dplyr:



                            library(dplyr)

                            df %>%
                            mutate(Result = case_when(
                            Team == Winner ~ "Winner",
                            Team != Winner ~ "Loser",
                            is.na(Winner) ~ "No result"
                            ))


                            # Team Winner Result
                            # 1 T1 T1 Winner
                            # 2 T2 T1 Loser
                            # 3 T2 <NA> No result
                            # 4 T3 <NA> No result


                            Data:



                            tt <- "Team     Winner
                            T1 T1
                            T2 T1
                            T2 NA
                            T3 NA"

                            df <- read.table(text=tt, header = T, stringsAsFactors = F)






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Nov 21 '18 at 8:34









                            RLave

                            3,5051922




                            3,5051922























                                2














                                You can use dplyr::if_else(), as I learned, it is strict, because it checks the data type and it handles the NAs, making code simpler:



                                 df %>% mutate(Result = if_else( Team==Winner, "Winner", "Loser", missing ='No result'))
                                Team Winner Result
                                1 T1 T1 Winner
                                2 T2 T1 Loser
                                3 T2 <NA> No result
                                4 T3 <NA> No result


                                Despite, looking at the one-liner solution here, for your example data, it's not the fastest (the winner is the @Tim Biegeleisen 's answer, +1):



                                Unit: microseconds
                                expr min lq mean median uq max neval cld
                                IF_ELSE 893.013 974.5060 1176.35331 1053.2260 1343.3590 2278.398 100 b
                                IFELSE 20.481 34.3475 49.57934 47.3605 58.0275 143.361 100 a
                                CASE 1067.946 1152.4255 1423.41426 1226.0255 1721.3850 4108.795 100 c


                                So I can figure out a trade off between simplicity (that is subjective, of course) and more control (that is objective, due the nature of the functions), and velocity (if it's an issue to you, looking your real data, but it's more objective).






                                share|improve this answer




























                                  2














                                  You can use dplyr::if_else(), as I learned, it is strict, because it checks the data type and it handles the NAs, making code simpler:



                                   df %>% mutate(Result = if_else( Team==Winner, "Winner", "Loser", missing ='No result'))
                                  Team Winner Result
                                  1 T1 T1 Winner
                                  2 T2 T1 Loser
                                  3 T2 <NA> No result
                                  4 T3 <NA> No result


                                  Despite, looking at the one-liner solution here, for your example data, it's not the fastest (the winner is the @Tim Biegeleisen 's answer, +1):



                                  Unit: microseconds
                                  expr min lq mean median uq max neval cld
                                  IF_ELSE 893.013 974.5060 1176.35331 1053.2260 1343.3590 2278.398 100 b
                                  IFELSE 20.481 34.3475 49.57934 47.3605 58.0275 143.361 100 a
                                  CASE 1067.946 1152.4255 1423.41426 1226.0255 1721.3850 4108.795 100 c


                                  So I can figure out a trade off between simplicity (that is subjective, of course) and more control (that is objective, due the nature of the functions), and velocity (if it's an issue to you, looking your real data, but it's more objective).






                                  share|improve this answer


























                                    2












                                    2








                                    2






                                    You can use dplyr::if_else(), as I learned, it is strict, because it checks the data type and it handles the NAs, making code simpler:



                                     df %>% mutate(Result = if_else( Team==Winner, "Winner", "Loser", missing ='No result'))
                                    Team Winner Result
                                    1 T1 T1 Winner
                                    2 T2 T1 Loser
                                    3 T2 <NA> No result
                                    4 T3 <NA> No result


                                    Despite, looking at the one-liner solution here, for your example data, it's not the fastest (the winner is the @Tim Biegeleisen 's answer, +1):



                                    Unit: microseconds
                                    expr min lq mean median uq max neval cld
                                    IF_ELSE 893.013 974.5060 1176.35331 1053.2260 1343.3590 2278.398 100 b
                                    IFELSE 20.481 34.3475 49.57934 47.3605 58.0275 143.361 100 a
                                    CASE 1067.946 1152.4255 1423.41426 1226.0255 1721.3850 4108.795 100 c


                                    So I can figure out a trade off between simplicity (that is subjective, of course) and more control (that is objective, due the nature of the functions), and velocity (if it's an issue to you, looking your real data, but it's more objective).






                                    share|improve this answer














                                    You can use dplyr::if_else(), as I learned, it is strict, because it checks the data type and it handles the NAs, making code simpler:



                                     df %>% mutate(Result = if_else( Team==Winner, "Winner", "Loser", missing ='No result'))
                                    Team Winner Result
                                    1 T1 T1 Winner
                                    2 T2 T1 Loser
                                    3 T2 <NA> No result
                                    4 T3 <NA> No result


                                    Despite, looking at the one-liner solution here, for your example data, it's not the fastest (the winner is the @Tim Biegeleisen 's answer, +1):



                                    Unit: microseconds
                                    expr min lq mean median uq max neval cld
                                    IF_ELSE 893.013 974.5060 1176.35331 1053.2260 1343.3590 2278.398 100 b
                                    IFELSE 20.481 34.3475 49.57934 47.3605 58.0275 143.361 100 a
                                    CASE 1067.946 1152.4255 1423.41426 1226.0255 1721.3850 4108.795 100 c


                                    So I can figure out a trade off between simplicity (that is subjective, of course) and more control (that is objective, due the nature of the functions), and velocity (if it's an issue to you, looking your real data, but it's more objective).







                                    share|improve this answer














                                    share|improve this answer



                                    share|improve this answer








                                    edited Nov 21 '18 at 10:23

























                                    answered Nov 21 '18 at 8:51









                                    s_t

                                    3,1282929




                                    3,1282929























                                        1














                                        Try this logic:



                                        df$result <- ifelse(is.na(df$Winner), "no result",
                                        ifelse(df$Team==df$Winner, "winner", "loser"))
                                        df

                                        Team Winner result
                                        1 T1 T1 winner
                                        2 T2 T1 loser
                                        3 T2 <NA> no result
                                        4 T3 <NA> no result





                                        share|improve this answer























                                        • This is give NA where I want it to be losser
                                          – Praveen Chougale
                                          Nov 21 '18 at 8:35










                                        • Answer updated.
                                          – Tim Biegeleisen
                                          Nov 21 '18 at 8:48
















                                        1














                                        Try this logic:



                                        df$result <- ifelse(is.na(df$Winner), "no result",
                                        ifelse(df$Team==df$Winner, "winner", "loser"))
                                        df

                                        Team Winner result
                                        1 T1 T1 winner
                                        2 T2 T1 loser
                                        3 T2 <NA> no result
                                        4 T3 <NA> no result





                                        share|improve this answer























                                        • This is give NA where I want it to be losser
                                          – Praveen Chougale
                                          Nov 21 '18 at 8:35










                                        • Answer updated.
                                          – Tim Biegeleisen
                                          Nov 21 '18 at 8:48














                                        1












                                        1








                                        1






                                        Try this logic:



                                        df$result <- ifelse(is.na(df$Winner), "no result",
                                        ifelse(df$Team==df$Winner, "winner", "loser"))
                                        df

                                        Team Winner result
                                        1 T1 T1 winner
                                        2 T2 T1 loser
                                        3 T2 <NA> no result
                                        4 T3 <NA> no result





                                        share|improve this answer














                                        Try this logic:



                                        df$result <- ifelse(is.na(df$Winner), "no result",
                                        ifelse(df$Team==df$Winner, "winner", "loser"))
                                        df

                                        Team Winner result
                                        1 T1 T1 winner
                                        2 T2 T1 loser
                                        3 T2 <NA> no result
                                        4 T3 <NA> no result






                                        share|improve this answer














                                        share|improve this answer



                                        share|improve this answer








                                        edited Nov 21 '18 at 8:48

























                                        answered Nov 21 '18 at 8:32









                                        Tim Biegeleisen

                                        217k1386139




                                        217k1386139












                                        • This is give NA where I want it to be losser
                                          – Praveen Chougale
                                          Nov 21 '18 at 8:35










                                        • Answer updated.
                                          – Tim Biegeleisen
                                          Nov 21 '18 at 8:48


















                                        • This is give NA where I want it to be losser
                                          – Praveen Chougale
                                          Nov 21 '18 at 8:35










                                        • Answer updated.
                                          – Tim Biegeleisen
                                          Nov 21 '18 at 8:48
















                                        This is give NA where I want it to be losser
                                        – Praveen Chougale
                                        Nov 21 '18 at 8:35




                                        This is give NA where I want it to be losser
                                        – Praveen Chougale
                                        Nov 21 '18 at 8:35












                                        Answer updated.
                                        – Tim Biegeleisen
                                        Nov 21 '18 at 8:48




                                        Answer updated.
                                        – Tim Biegeleisen
                                        Nov 21 '18 at 8:48


















                                        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.





                                        Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                        Please pay close attention to the following guidance:


                                        • 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%2f53407875%2fhow-to-write-ifelse-statement-with-multiple-conditions-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

                                        Wiesbaden

                                        Marschland

                                        Dieringhausen