Set all vector elements to NA in a list of vectors












6














How can I set all vector elements to NA in a list of vectors?



Essentially, I'd like to keep an existing list's structure and names but empty all values, to fill them in later. I provide a minimal example with a couple solutions below. I prefer base and tidyverse (esp. purrr) solutions, but can get on board with any approach which is better than what I have below.



my_list <- list(A = c('a' = 1, 'b' = 2, 'c' = 3), B = c('x' = 10, 'y' = 20))
ret_list <- my_list

# Approach 1
for (element_name in names(my_list)) {
ret_list[[element_name]] <- NA
}

ret_list
# $A
# a b c
# NA NA NA
#
# $B
# x y
# NA NA

# Approach 2
lapply(my_list, function(x) {x <- NA; return(x)})
# $A
# a b c
# NA NA NA
#
# $B
# x y
# NA NA









share|improve this question




















  • 1




    both approaches seem fine to me (especially if you define the function in Approach 2 beforehand rather than anonymously inline). Why try to be cleverer than that? What specific shortcomings would you like to remedy?
    – Ben Bolker
    Dec 31 '18 at 23:27








  • 1




    Just taking an opportunity to understand R a little better. It seemed to me that this was such a common operation that there had to be a standard, best-practices approach.
    – lowndrul
    Dec 31 '18 at 23:40
















6














How can I set all vector elements to NA in a list of vectors?



Essentially, I'd like to keep an existing list's structure and names but empty all values, to fill them in later. I provide a minimal example with a couple solutions below. I prefer base and tidyverse (esp. purrr) solutions, but can get on board with any approach which is better than what I have below.



my_list <- list(A = c('a' = 1, 'b' = 2, 'c' = 3), B = c('x' = 10, 'y' = 20))
ret_list <- my_list

# Approach 1
for (element_name in names(my_list)) {
ret_list[[element_name]] <- NA
}

ret_list
# $A
# a b c
# NA NA NA
#
# $B
# x y
# NA NA

# Approach 2
lapply(my_list, function(x) {x <- NA; return(x)})
# $A
# a b c
# NA NA NA
#
# $B
# x y
# NA NA









share|improve this question




















  • 1




    both approaches seem fine to me (especially if you define the function in Approach 2 beforehand rather than anonymously inline). Why try to be cleverer than that? What specific shortcomings would you like to remedy?
    – Ben Bolker
    Dec 31 '18 at 23:27








  • 1




    Just taking an opportunity to understand R a little better. It seemed to me that this was such a common operation that there had to be a standard, best-practices approach.
    – lowndrul
    Dec 31 '18 at 23:40














6












6








6


1





How can I set all vector elements to NA in a list of vectors?



Essentially, I'd like to keep an existing list's structure and names but empty all values, to fill them in later. I provide a minimal example with a couple solutions below. I prefer base and tidyverse (esp. purrr) solutions, but can get on board with any approach which is better than what I have below.



my_list <- list(A = c('a' = 1, 'b' = 2, 'c' = 3), B = c('x' = 10, 'y' = 20))
ret_list <- my_list

# Approach 1
for (element_name in names(my_list)) {
ret_list[[element_name]] <- NA
}

ret_list
# $A
# a b c
# NA NA NA
#
# $B
# x y
# NA NA

# Approach 2
lapply(my_list, function(x) {x <- NA; return(x)})
# $A
# a b c
# NA NA NA
#
# $B
# x y
# NA NA









share|improve this question















How can I set all vector elements to NA in a list of vectors?



Essentially, I'd like to keep an existing list's structure and names but empty all values, to fill them in later. I provide a minimal example with a couple solutions below. I prefer base and tidyverse (esp. purrr) solutions, but can get on board with any approach which is better than what I have below.



my_list <- list(A = c('a' = 1, 'b' = 2, 'c' = 3), B = c('x' = 10, 'y' = 20))
ret_list <- my_list

# Approach 1
for (element_name in names(my_list)) {
ret_list[[element_name]] <- NA
}

ret_list
# $A
# a b c
# NA NA NA
#
# $B
# x y
# NA NA

# Approach 2
lapply(my_list, function(x) {x <- NA; return(x)})
# $A
# a b c
# NA NA NA
#
# $B
# x y
# NA NA






r






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 1 at 0:02

























asked Dec 31 '18 at 22:56









lowndrul

1,16521835




1,16521835








  • 1




    both approaches seem fine to me (especially if you define the function in Approach 2 beforehand rather than anonymously inline). Why try to be cleverer than that? What specific shortcomings would you like to remedy?
    – Ben Bolker
    Dec 31 '18 at 23:27








  • 1




    Just taking an opportunity to understand R a little better. It seemed to me that this was such a common operation that there had to be a standard, best-practices approach.
    – lowndrul
    Dec 31 '18 at 23:40














  • 1




    both approaches seem fine to me (especially if you define the function in Approach 2 beforehand rather than anonymously inline). Why try to be cleverer than that? What specific shortcomings would you like to remedy?
    – Ben Bolker
    Dec 31 '18 at 23:27








  • 1




    Just taking an opportunity to understand R a little better. It seemed to me that this was such a common operation that there had to be a standard, best-practices approach.
    – lowndrul
    Dec 31 '18 at 23:40








1




1




both approaches seem fine to me (especially if you define the function in Approach 2 beforehand rather than anonymously inline). Why try to be cleverer than that? What specific shortcomings would you like to remedy?
– Ben Bolker
Dec 31 '18 at 23:27






both approaches seem fine to me (especially if you define the function in Approach 2 beforehand rather than anonymously inline). Why try to be cleverer than that? What specific shortcomings would you like to remedy?
– Ben Bolker
Dec 31 '18 at 23:27






1




1




Just taking an opportunity to understand R a little better. It seemed to me that this was such a common operation that there had to be a standard, best-practices approach.
– lowndrul
Dec 31 '18 at 23:40




Just taking an opportunity to understand R a little better. It seemed to me that this was such a common operation that there had to be a standard, best-practices approach.
– lowndrul
Dec 31 '18 at 23:40












5 Answers
5






active

oldest

votes


















8














Here's another one for numeric vectors:



lapply(my_list, `*`, NA) # Instead of * it could also be +, -, etc.
# $A
# a b c
# NA NA NA
#
# $B
# x y
# NA NA


More generally,



lapply(my_list, replace, TRUE, NA)


and



lapply(ret_list, ifelse, NA, NA)





share|improve this answer























  • what is * called as in this context ?
    – YOLO
    Dec 31 '18 at 23:12






  • 1




    @YOLO, I'm not sure what you mean. The first approach is the same as lapply(my_list, function(x) x * NA), so * is the usual product, which results to NA when one of the factors is NA.
    – Julius Vainora
    Dec 31 '18 at 23:15





















7














You can use function is.na<- in a lapply loop.



ret_list <- lapply(my_list, `is.na<-`)
ret_list
#$A
# a b c
#NA NA NA
#
#$B
# x y
#NA NA





share|improve this answer





























    4














    another alternative with dplyr:



    lapply(my_list, function(x) dplyr::na_if(x,x))





    share|improve this answer





























      4














      If the list is not restricted to one level then use rapply.



      # test data modified from question
      my_list2 <- list(list(A = c(a = 1, b = 2, c = 3)), B = c(x = 10, y = 20))

      rapply(my_list2, function(x) replace(x, TRUE, NA), how = "list")


      which can also be written as:



      rapply(my_list2, replace, list = TRUE, values = NA, how = "list")





      share|improve this answer





























        3














        Another way around



        relist(replace( unlist(my_list), TRUE, NA ), skeleton = my_list)

        #$A
        # a b c
        #NA NA NA

        #$B
        # x y
        #NA NA





        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%2f53991996%2fset-all-vector-elements-to-na-in-a-list-of-vectors%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          5 Answers
          5






          active

          oldest

          votes








          5 Answers
          5






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          8














          Here's another one for numeric vectors:



          lapply(my_list, `*`, NA) # Instead of * it could also be +, -, etc.
          # $A
          # a b c
          # NA NA NA
          #
          # $B
          # x y
          # NA NA


          More generally,



          lapply(my_list, replace, TRUE, NA)


          and



          lapply(ret_list, ifelse, NA, NA)





          share|improve this answer























          • what is * called as in this context ?
            – YOLO
            Dec 31 '18 at 23:12






          • 1




            @YOLO, I'm not sure what you mean. The first approach is the same as lapply(my_list, function(x) x * NA), so * is the usual product, which results to NA when one of the factors is NA.
            – Julius Vainora
            Dec 31 '18 at 23:15


















          8














          Here's another one for numeric vectors:



          lapply(my_list, `*`, NA) # Instead of * it could also be +, -, etc.
          # $A
          # a b c
          # NA NA NA
          #
          # $B
          # x y
          # NA NA


          More generally,



          lapply(my_list, replace, TRUE, NA)


          and



          lapply(ret_list, ifelse, NA, NA)





          share|improve this answer























          • what is * called as in this context ?
            – YOLO
            Dec 31 '18 at 23:12






          • 1




            @YOLO, I'm not sure what you mean. The first approach is the same as lapply(my_list, function(x) x * NA), so * is the usual product, which results to NA when one of the factors is NA.
            – Julius Vainora
            Dec 31 '18 at 23:15
















          8












          8








          8






          Here's another one for numeric vectors:



          lapply(my_list, `*`, NA) # Instead of * it could also be +, -, etc.
          # $A
          # a b c
          # NA NA NA
          #
          # $B
          # x y
          # NA NA


          More generally,



          lapply(my_list, replace, TRUE, NA)


          and



          lapply(ret_list, ifelse, NA, NA)





          share|improve this answer














          Here's another one for numeric vectors:



          lapply(my_list, `*`, NA) # Instead of * it could also be +, -, etc.
          # $A
          # a b c
          # NA NA NA
          #
          # $B
          # x y
          # NA NA


          More generally,



          lapply(my_list, replace, TRUE, NA)


          and



          lapply(ret_list, ifelse, NA, NA)






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited 2 days ago

























          answered Dec 31 '18 at 22:58









          Julius Vainora

          32.7k75979




          32.7k75979












          • what is * called as in this context ?
            – YOLO
            Dec 31 '18 at 23:12






          • 1




            @YOLO, I'm not sure what you mean. The first approach is the same as lapply(my_list, function(x) x * NA), so * is the usual product, which results to NA when one of the factors is NA.
            – Julius Vainora
            Dec 31 '18 at 23:15




















          • what is * called as in this context ?
            – YOLO
            Dec 31 '18 at 23:12






          • 1




            @YOLO, I'm not sure what you mean. The first approach is the same as lapply(my_list, function(x) x * NA), so * is the usual product, which results to NA when one of the factors is NA.
            – Julius Vainora
            Dec 31 '18 at 23:15


















          what is * called as in this context ?
          – YOLO
          Dec 31 '18 at 23:12




          what is * called as in this context ?
          – YOLO
          Dec 31 '18 at 23:12




          1




          1




          @YOLO, I'm not sure what you mean. The first approach is the same as lapply(my_list, function(x) x * NA), so * is the usual product, which results to NA when one of the factors is NA.
          – Julius Vainora
          Dec 31 '18 at 23:15






          @YOLO, I'm not sure what you mean. The first approach is the same as lapply(my_list, function(x) x * NA), so * is the usual product, which results to NA when one of the factors is NA.
          – Julius Vainora
          Dec 31 '18 at 23:15















          7














          You can use function is.na<- in a lapply loop.



          ret_list <- lapply(my_list, `is.na<-`)
          ret_list
          #$A
          # a b c
          #NA NA NA
          #
          #$B
          # x y
          #NA NA





          share|improve this answer


























            7














            You can use function is.na<- in a lapply loop.



            ret_list <- lapply(my_list, `is.na<-`)
            ret_list
            #$A
            # a b c
            #NA NA NA
            #
            #$B
            # x y
            #NA NA





            share|improve this answer
























              7












              7








              7






              You can use function is.na<- in a lapply loop.



              ret_list <- lapply(my_list, `is.na<-`)
              ret_list
              #$A
              # a b c
              #NA NA NA
              #
              #$B
              # x y
              #NA NA





              share|improve this answer












              You can use function is.na<- in a lapply loop.



              ret_list <- lapply(my_list, `is.na<-`)
              ret_list
              #$A
              # a b c
              #NA NA NA
              #
              #$B
              # x y
              #NA NA






              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Dec 31 '18 at 23:16









              Rui Barradas

              16.1k41730




              16.1k41730























                  4














                  another alternative with dplyr:



                  lapply(my_list, function(x) dplyr::na_if(x,x))





                  share|improve this answer


























                    4














                    another alternative with dplyr:



                    lapply(my_list, function(x) dplyr::na_if(x,x))





                    share|improve this answer
























                      4












                      4








                      4






                      another alternative with dplyr:



                      lapply(my_list, function(x) dplyr::na_if(x,x))





                      share|improve this answer












                      another alternative with dplyr:



                      lapply(my_list, function(x) dplyr::na_if(x,x))






                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Dec 31 '18 at 23:36









                      Mankind_008

                      1,4762312




                      1,4762312























                          4














                          If the list is not restricted to one level then use rapply.



                          # test data modified from question
                          my_list2 <- list(list(A = c(a = 1, b = 2, c = 3)), B = c(x = 10, y = 20))

                          rapply(my_list2, function(x) replace(x, TRUE, NA), how = "list")


                          which can also be written as:



                          rapply(my_list2, replace, list = TRUE, values = NA, how = "list")





                          share|improve this answer


























                            4














                            If the list is not restricted to one level then use rapply.



                            # test data modified from question
                            my_list2 <- list(list(A = c(a = 1, b = 2, c = 3)), B = c(x = 10, y = 20))

                            rapply(my_list2, function(x) replace(x, TRUE, NA), how = "list")


                            which can also be written as:



                            rapply(my_list2, replace, list = TRUE, values = NA, how = "list")





                            share|improve this answer
























                              4












                              4








                              4






                              If the list is not restricted to one level then use rapply.



                              # test data modified from question
                              my_list2 <- list(list(A = c(a = 1, b = 2, c = 3)), B = c(x = 10, y = 20))

                              rapply(my_list2, function(x) replace(x, TRUE, NA), how = "list")


                              which can also be written as:



                              rapply(my_list2, replace, list = TRUE, values = NA, how = "list")





                              share|improve this answer












                              If the list is not restricted to one level then use rapply.



                              # test data modified from question
                              my_list2 <- list(list(A = c(a = 1, b = 2, c = 3)), B = c(x = 10, y = 20))

                              rapply(my_list2, function(x) replace(x, TRUE, NA), how = "list")


                              which can also be written as:



                              rapply(my_list2, replace, list = TRUE, values = NA, how = "list")






                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Jan 1 at 0:10









                              G. Grothendieck

                              145k9126231




                              145k9126231























                                  3














                                  Another way around



                                  relist(replace( unlist(my_list), TRUE, NA ), skeleton = my_list)

                                  #$A
                                  # a b c
                                  #NA NA NA

                                  #$B
                                  # x y
                                  #NA NA





                                  share|improve this answer


























                                    3














                                    Another way around



                                    relist(replace( unlist(my_list), TRUE, NA ), skeleton = my_list)

                                    #$A
                                    # a b c
                                    #NA NA NA

                                    #$B
                                    # x y
                                    #NA NA





                                    share|improve this answer
























                                      3












                                      3








                                      3






                                      Another way around



                                      relist(replace( unlist(my_list), TRUE, NA ), skeleton = my_list)

                                      #$A
                                      # a b c
                                      #NA NA NA

                                      #$B
                                      # x y
                                      #NA NA





                                      share|improve this answer












                                      Another way around



                                      relist(replace( unlist(my_list), TRUE, NA ), skeleton = my_list)

                                      #$A
                                      # a b c
                                      #NA NA NA

                                      #$B
                                      # x y
                                      #NA NA






                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Dec 31 '18 at 23:30









                                      989

                                      8,91251834




                                      8,91251834






























                                          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%2f53991996%2fset-all-vector-elements-to-na-in-a-list-of-vectors%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

                                          "Incorrect syntax near the keyword 'ON'. (on update cascade, on delete cascade,)

                                          Alcedinidae

                                          RAC Tourist Trophy