Replacing an element within a vector in a list












1















I have a list of vectors that looks like



[[1]][1] 1 1 2

[[2]]
[1] 1 1 2

[[3]]
[1] 2 1 1

[[4]]
[1] 2 2 2


I would like the replace the first component of each of the vectors with a 9. I have tried



out <- append(vecs2T2[[1]], y, after=0)


but this just adds an 9 in at the start and does not replace it (see below).



[1] 9 1 1 2


I would like this entry to read 912.










share|improve this question





























    1















    I have a list of vectors that looks like



    [[1]][1] 1 1 2

    [[2]]
    [1] 1 1 2

    [[3]]
    [1] 2 1 1

    [[4]]
    [1] 2 2 2


    I would like the replace the first component of each of the vectors with a 9. I have tried



    out <- append(vecs2T2[[1]], y, after=0)


    but this just adds an 9 in at the start and does not replace it (see below).



    [1] 9 1 1 2


    I would like this entry to read 912.










    share|improve this question



























      1












      1








      1








      I have a list of vectors that looks like



      [[1]][1] 1 1 2

      [[2]]
      [1] 1 1 2

      [[3]]
      [1] 2 1 1

      [[4]]
      [1] 2 2 2


      I would like the replace the first component of each of the vectors with a 9. I have tried



      out <- append(vecs2T2[[1]], y, after=0)


      but this just adds an 9 in at the start and does not replace it (see below).



      [1] 9 1 1 2


      I would like this entry to read 912.










      share|improve this question
















      I have a list of vectors that looks like



      [[1]][1] 1 1 2

      [[2]]
      [1] 1 1 2

      [[3]]
      [1] 2 1 1

      [[4]]
      [1] 2 2 2


      I would like the replace the first component of each of the vectors with a 9. I have tried



      out <- append(vecs2T2[[1]], y, after=0)


      but this just adds an 9 in at the start and does not replace it (see below).



      [1] 9 1 1 2


      I would like this entry to read 912.







      r






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 21 '18 at 14:35









      Sotos

      29.8k51640




      29.8k51640










      asked Nov 21 '18 at 14:23









      Sarah Sarah

      65




      65
























          2 Answers
          2






          active

          oldest

          votes


















          1














          lapply(ll, replace, 1, 9)


          This goes vector by vector, and replaces the 1st item with 9. (Replace's arguments are: (data, list-of-indexes, list-of-values), with the list of values recycled to be as long as the list of indexes.)



          replace() is just defined as:



          replace <- function (x, list, values) {
          x[list] <- values
          x
          }


          so you can also use that method.



          lapply(ll, function(x) { x[1] <- 9 ; x })


          You can use either with purrr::map(), too:



          purrr::map(ll, ~{ .x[1] <- 9 ; .x })
          purrr::map(ll, replace, 1, 9)


          Head-to-head (not the best microbenchmark setup in the world tho):



          microbenchmark::microbenchmark(
          purr_repl = purrr::map(ll, replace, 1, 9),
          purr_op = purrr::map(ll, ~{ .x[1] <- 9 ; .x }),
          lapp_repl = lapply(ll, replace, 1, 9),
          lapp_op = lapply(ll, function(x) { x[1] <- 9 ; x }),
          Map = Map(function(x, y)c(x, y[-1]), 9, ll)
          )
          ## Unit: microseconds
          ## expr min lq mean median uq max neval
          ## purr_repl 27.510 29.7555 49.98242 31.4735 33.4805 1506.400 100
          ## purr_op 84.415 86.9550 125.07364 90.0665 98.9465 2423.406 100
          ## lapp_repl 4.422 4.8350 5.94472 5.1965 5.5930 34.947 100
          ## lapp_op 4.672 5.4250 19.14590 5.9045 6.5015 1215.477 100
          ## Map 10.670 12.2490 28.94712 13.5935 14.7170 1238.311 100





          share|improve this answer


























          • That worked perfectly. Thank you

            – Sarah
            Nov 21 '18 at 14:31











          • Happy to hear. Don't forget to accept! :)

            – iod
            Nov 21 '18 at 14:33











          • @hrbrmstr - thanks for all the edits, but the bottom line from your comparison at the bottom is that my original solution is the fastest one, by a lot, isn't it?

            – iod
            Nov 21 '18 at 14:42











          • Yep, hence why I added it. Your solution was 👍🏼 (some folks have their heads stuck in the tidyverse so they'll appreciate the purrr additions despite the serious performance hit). Adding the alternates outside your answer seemed wrong since it's all the same thing (just less performant)

            – hrbrmstr
            Nov 21 '18 at 14:45





















          0














          Another idea is to use Map and concatenate 9 with the each vector minus its first element



          Map(function(x, y)c(x, y[-1]), 9, l1)





          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%2f53414188%2freplacing-an-element-within-a-vector-in-a-list%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            1














            lapply(ll, replace, 1, 9)


            This goes vector by vector, and replaces the 1st item with 9. (Replace's arguments are: (data, list-of-indexes, list-of-values), with the list of values recycled to be as long as the list of indexes.)



            replace() is just defined as:



            replace <- function (x, list, values) {
            x[list] <- values
            x
            }


            so you can also use that method.



            lapply(ll, function(x) { x[1] <- 9 ; x })


            You can use either with purrr::map(), too:



            purrr::map(ll, ~{ .x[1] <- 9 ; .x })
            purrr::map(ll, replace, 1, 9)


            Head-to-head (not the best microbenchmark setup in the world tho):



            microbenchmark::microbenchmark(
            purr_repl = purrr::map(ll, replace, 1, 9),
            purr_op = purrr::map(ll, ~{ .x[1] <- 9 ; .x }),
            lapp_repl = lapply(ll, replace, 1, 9),
            lapp_op = lapply(ll, function(x) { x[1] <- 9 ; x }),
            Map = Map(function(x, y)c(x, y[-1]), 9, ll)
            )
            ## Unit: microseconds
            ## expr min lq mean median uq max neval
            ## purr_repl 27.510 29.7555 49.98242 31.4735 33.4805 1506.400 100
            ## purr_op 84.415 86.9550 125.07364 90.0665 98.9465 2423.406 100
            ## lapp_repl 4.422 4.8350 5.94472 5.1965 5.5930 34.947 100
            ## lapp_op 4.672 5.4250 19.14590 5.9045 6.5015 1215.477 100
            ## Map 10.670 12.2490 28.94712 13.5935 14.7170 1238.311 100





            share|improve this answer


























            • That worked perfectly. Thank you

              – Sarah
              Nov 21 '18 at 14:31











            • Happy to hear. Don't forget to accept! :)

              – iod
              Nov 21 '18 at 14:33











            • @hrbrmstr - thanks for all the edits, but the bottom line from your comparison at the bottom is that my original solution is the fastest one, by a lot, isn't it?

              – iod
              Nov 21 '18 at 14:42











            • Yep, hence why I added it. Your solution was 👍🏼 (some folks have their heads stuck in the tidyverse so they'll appreciate the purrr additions despite the serious performance hit). Adding the alternates outside your answer seemed wrong since it's all the same thing (just less performant)

              – hrbrmstr
              Nov 21 '18 at 14:45


















            1














            lapply(ll, replace, 1, 9)


            This goes vector by vector, and replaces the 1st item with 9. (Replace's arguments are: (data, list-of-indexes, list-of-values), with the list of values recycled to be as long as the list of indexes.)



            replace() is just defined as:



            replace <- function (x, list, values) {
            x[list] <- values
            x
            }


            so you can also use that method.



            lapply(ll, function(x) { x[1] <- 9 ; x })


            You can use either with purrr::map(), too:



            purrr::map(ll, ~{ .x[1] <- 9 ; .x })
            purrr::map(ll, replace, 1, 9)


            Head-to-head (not the best microbenchmark setup in the world tho):



            microbenchmark::microbenchmark(
            purr_repl = purrr::map(ll, replace, 1, 9),
            purr_op = purrr::map(ll, ~{ .x[1] <- 9 ; .x }),
            lapp_repl = lapply(ll, replace, 1, 9),
            lapp_op = lapply(ll, function(x) { x[1] <- 9 ; x }),
            Map = Map(function(x, y)c(x, y[-1]), 9, ll)
            )
            ## Unit: microseconds
            ## expr min lq mean median uq max neval
            ## purr_repl 27.510 29.7555 49.98242 31.4735 33.4805 1506.400 100
            ## purr_op 84.415 86.9550 125.07364 90.0665 98.9465 2423.406 100
            ## lapp_repl 4.422 4.8350 5.94472 5.1965 5.5930 34.947 100
            ## lapp_op 4.672 5.4250 19.14590 5.9045 6.5015 1215.477 100
            ## Map 10.670 12.2490 28.94712 13.5935 14.7170 1238.311 100





            share|improve this answer


























            • That worked perfectly. Thank you

              – Sarah
              Nov 21 '18 at 14:31











            • Happy to hear. Don't forget to accept! :)

              – iod
              Nov 21 '18 at 14:33











            • @hrbrmstr - thanks for all the edits, but the bottom line from your comparison at the bottom is that my original solution is the fastest one, by a lot, isn't it?

              – iod
              Nov 21 '18 at 14:42











            • Yep, hence why I added it. Your solution was 👍🏼 (some folks have their heads stuck in the tidyverse so they'll appreciate the purrr additions despite the serious performance hit). Adding the alternates outside your answer seemed wrong since it's all the same thing (just less performant)

              – hrbrmstr
              Nov 21 '18 at 14:45
















            1












            1








            1







            lapply(ll, replace, 1, 9)


            This goes vector by vector, and replaces the 1st item with 9. (Replace's arguments are: (data, list-of-indexes, list-of-values), with the list of values recycled to be as long as the list of indexes.)



            replace() is just defined as:



            replace <- function (x, list, values) {
            x[list] <- values
            x
            }


            so you can also use that method.



            lapply(ll, function(x) { x[1] <- 9 ; x })


            You can use either with purrr::map(), too:



            purrr::map(ll, ~{ .x[1] <- 9 ; .x })
            purrr::map(ll, replace, 1, 9)


            Head-to-head (not the best microbenchmark setup in the world tho):



            microbenchmark::microbenchmark(
            purr_repl = purrr::map(ll, replace, 1, 9),
            purr_op = purrr::map(ll, ~{ .x[1] <- 9 ; .x }),
            lapp_repl = lapply(ll, replace, 1, 9),
            lapp_op = lapply(ll, function(x) { x[1] <- 9 ; x }),
            Map = Map(function(x, y)c(x, y[-1]), 9, ll)
            )
            ## Unit: microseconds
            ## expr min lq mean median uq max neval
            ## purr_repl 27.510 29.7555 49.98242 31.4735 33.4805 1506.400 100
            ## purr_op 84.415 86.9550 125.07364 90.0665 98.9465 2423.406 100
            ## lapp_repl 4.422 4.8350 5.94472 5.1965 5.5930 34.947 100
            ## lapp_op 4.672 5.4250 19.14590 5.9045 6.5015 1215.477 100
            ## Map 10.670 12.2490 28.94712 13.5935 14.7170 1238.311 100





            share|improve this answer















            lapply(ll, replace, 1, 9)


            This goes vector by vector, and replaces the 1st item with 9. (Replace's arguments are: (data, list-of-indexes, list-of-values), with the list of values recycled to be as long as the list of indexes.)



            replace() is just defined as:



            replace <- function (x, list, values) {
            x[list] <- values
            x
            }


            so you can also use that method.



            lapply(ll, function(x) { x[1] <- 9 ; x })


            You can use either with purrr::map(), too:



            purrr::map(ll, ~{ .x[1] <- 9 ; .x })
            purrr::map(ll, replace, 1, 9)


            Head-to-head (not the best microbenchmark setup in the world tho):



            microbenchmark::microbenchmark(
            purr_repl = purrr::map(ll, replace, 1, 9),
            purr_op = purrr::map(ll, ~{ .x[1] <- 9 ; .x }),
            lapp_repl = lapply(ll, replace, 1, 9),
            lapp_op = lapply(ll, function(x) { x[1] <- 9 ; x }),
            Map = Map(function(x, y)c(x, y[-1]), 9, ll)
            )
            ## Unit: microseconds
            ## expr min lq mean median uq max neval
            ## purr_repl 27.510 29.7555 49.98242 31.4735 33.4805 1506.400 100
            ## purr_op 84.415 86.9550 125.07364 90.0665 98.9465 2423.406 100
            ## lapp_repl 4.422 4.8350 5.94472 5.1965 5.5930 34.947 100
            ## lapp_op 4.672 5.4250 19.14590 5.9045 6.5015 1215.477 100
            ## Map 10.670 12.2490 28.94712 13.5935 14.7170 1238.311 100






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 21 '18 at 14:35









            hrbrmstr

            61k688150




            61k688150










            answered Nov 21 '18 at 14:29









            iodiod

            3,8432722




            3,8432722













            • That worked perfectly. Thank you

              – Sarah
              Nov 21 '18 at 14:31











            • Happy to hear. Don't forget to accept! :)

              – iod
              Nov 21 '18 at 14:33











            • @hrbrmstr - thanks for all the edits, but the bottom line from your comparison at the bottom is that my original solution is the fastest one, by a lot, isn't it?

              – iod
              Nov 21 '18 at 14:42











            • Yep, hence why I added it. Your solution was 👍🏼 (some folks have their heads stuck in the tidyverse so they'll appreciate the purrr additions despite the serious performance hit). Adding the alternates outside your answer seemed wrong since it's all the same thing (just less performant)

              – hrbrmstr
              Nov 21 '18 at 14:45





















            • That worked perfectly. Thank you

              – Sarah
              Nov 21 '18 at 14:31











            • Happy to hear. Don't forget to accept! :)

              – iod
              Nov 21 '18 at 14:33











            • @hrbrmstr - thanks for all the edits, but the bottom line from your comparison at the bottom is that my original solution is the fastest one, by a lot, isn't it?

              – iod
              Nov 21 '18 at 14:42











            • Yep, hence why I added it. Your solution was 👍🏼 (some folks have their heads stuck in the tidyverse so they'll appreciate the purrr additions despite the serious performance hit). Adding the alternates outside your answer seemed wrong since it's all the same thing (just less performant)

              – hrbrmstr
              Nov 21 '18 at 14:45



















            That worked perfectly. Thank you

            – Sarah
            Nov 21 '18 at 14:31





            That worked perfectly. Thank you

            – Sarah
            Nov 21 '18 at 14:31













            Happy to hear. Don't forget to accept! :)

            – iod
            Nov 21 '18 at 14:33





            Happy to hear. Don't forget to accept! :)

            – iod
            Nov 21 '18 at 14:33













            @hrbrmstr - thanks for all the edits, but the bottom line from your comparison at the bottom is that my original solution is the fastest one, by a lot, isn't it?

            – iod
            Nov 21 '18 at 14:42





            @hrbrmstr - thanks for all the edits, but the bottom line from your comparison at the bottom is that my original solution is the fastest one, by a lot, isn't it?

            – iod
            Nov 21 '18 at 14:42













            Yep, hence why I added it. Your solution was 👍🏼 (some folks have their heads stuck in the tidyverse so they'll appreciate the purrr additions despite the serious performance hit). Adding the alternates outside your answer seemed wrong since it's all the same thing (just less performant)

            – hrbrmstr
            Nov 21 '18 at 14:45







            Yep, hence why I added it. Your solution was 👍🏼 (some folks have their heads stuck in the tidyverse so they'll appreciate the purrr additions despite the serious performance hit). Adding the alternates outside your answer seemed wrong since it's all the same thing (just less performant)

            – hrbrmstr
            Nov 21 '18 at 14:45















            0














            Another idea is to use Map and concatenate 9 with the each vector minus its first element



            Map(function(x, y)c(x, y[-1]), 9, l1)





            share|improve this answer




























              0














              Another idea is to use Map and concatenate 9 with the each vector minus its first element



              Map(function(x, y)c(x, y[-1]), 9, l1)





              share|improve this answer


























                0












                0








                0







                Another idea is to use Map and concatenate 9 with the each vector minus its first element



                Map(function(x, y)c(x, y[-1]), 9, l1)





                share|improve this answer













                Another idea is to use Map and concatenate 9 with the each vector minus its first element



                Map(function(x, y)c(x, y[-1]), 9, l1)






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 21 '18 at 14:35









                SotosSotos

                29.8k51640




                29.8k51640






























                    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%2f53414188%2freplacing-an-element-within-a-vector-in-a-list%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

                    'app-layout' is not a known element: how to share Component with different Modules

                    android studio warns about leanback feature tag usage required on manifest while using Unity exported app?

                    WPF add header to Image with URL pettitions [duplicate]