Operation along the same column given a logical condition












1















I have a dataframe of this form



distance city obs
9 0 1
5 1 2
7 0 3
6 0 4
5 0 5
10 1 6
11 0 7
15 0 8


I would like to create a new column "difference" which computes the difference of the values in the column "distance" between each observation and its closest (in terms of values in the column distance) city.



In other words I want to have something like this



    distance city obs difference
9 0 1 1
5 1 2 0
7 0 3 2
6 0 4 1
5 0 5 0
10 1 6 0
11 0 7 1
15 0 8 5


where the first obs in the new column has 1 because this is the difference between distances 9 and 10, which are the values in the column distance associated with observation 1 and its closest city (obs 6 in this case) respectively. The same reasoning applies for the other obs. For instance obs 3 presents a difference of 2 since this represents the difference between the values in the column distance between obs 3 itself and its closest city, which in this is case is observation 2. Cities themselves present 0.



Can anyone help me with this??



Many many thanks.










share|improve this question



























    1















    I have a dataframe of this form



    distance city obs
    9 0 1
    5 1 2
    7 0 3
    6 0 4
    5 0 5
    10 1 6
    11 0 7
    15 0 8


    I would like to create a new column "difference" which computes the difference of the values in the column "distance" between each observation and its closest (in terms of values in the column distance) city.



    In other words I want to have something like this



        distance city obs difference
    9 0 1 1
    5 1 2 0
    7 0 3 2
    6 0 4 1
    5 0 5 0
    10 1 6 0
    11 0 7 1
    15 0 8 5


    where the first obs in the new column has 1 because this is the difference between distances 9 and 10, which are the values in the column distance associated with observation 1 and its closest city (obs 6 in this case) respectively. The same reasoning applies for the other obs. For instance obs 3 presents a difference of 2 since this represents the difference between the values in the column distance between obs 3 itself and its closest city, which in this is case is observation 2. Cities themselves present 0.



    Can anyone help me with this??



    Many many thanks.










    share|improve this question

























      1












      1








      1








      I have a dataframe of this form



      distance city obs
      9 0 1
      5 1 2
      7 0 3
      6 0 4
      5 0 5
      10 1 6
      11 0 7
      15 0 8


      I would like to create a new column "difference" which computes the difference of the values in the column "distance" between each observation and its closest (in terms of values in the column distance) city.



      In other words I want to have something like this



          distance city obs difference
      9 0 1 1
      5 1 2 0
      7 0 3 2
      6 0 4 1
      5 0 5 0
      10 1 6 0
      11 0 7 1
      15 0 8 5


      where the first obs in the new column has 1 because this is the difference between distances 9 and 10, which are the values in the column distance associated with observation 1 and its closest city (obs 6 in this case) respectively. The same reasoning applies for the other obs. For instance obs 3 presents a difference of 2 since this represents the difference between the values in the column distance between obs 3 itself and its closest city, which in this is case is observation 2. Cities themselves present 0.



      Can anyone help me with this??



      Many many thanks.










      share|improve this question














      I have a dataframe of this form



      distance city obs
      9 0 1
      5 1 2
      7 0 3
      6 0 4
      5 0 5
      10 1 6
      11 0 7
      15 0 8


      I would like to create a new column "difference" which computes the difference of the values in the column "distance" between each observation and its closest (in terms of values in the column distance) city.



      In other words I want to have something like this



          distance city obs difference
      9 0 1 1
      5 1 2 0
      7 0 3 2
      6 0 4 1
      5 0 5 0
      10 1 6 0
      11 0 7 1
      15 0 8 5


      where the first obs in the new column has 1 because this is the difference between distances 9 and 10, which are the values in the column distance associated with observation 1 and its closest city (obs 6 in this case) respectively. The same reasoning applies for the other obs. For instance obs 3 presents a difference of 2 since this represents the difference between the values in the column distance between obs 3 itself and its closest city, which in this is case is observation 2. Cities themselves present 0.



      Can anyone help me with this??



      Many many thanks.







      r






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 13 '18 at 21:18









      Marco MelloMarco Mello

      558




      558
























          2 Answers
          2






          active

          oldest

          votes


















          2














          Here's a dplyr solution where you find the minimum distance to any of the cities:



          library(dplyr)
          df %>% rowwise %>% mutate(difference = min(abs(df$distance[df$city == 1] - distance)))
          #Source: local data frame [8 x 4]
          #Groups: <by row>
          #
          # A tibble: 8 x 4
          # distance city obs difference
          # <int> <int> <int> <int>
          #1 9 0 1 1
          #2 5 1 2 0
          #3 7 0 3 2
          #4 6 0 4 1
          #5 5 0 5 0
          #6 10 1 6 0
          #7 11 0 7 1
          #8 15 0 8 5


          And here is a base-r approach:



          df$difference <- sapply(df$distance,function(x)  min(abs(df$distance[df$city == 1] - x)))
          df
          # distance city obs difference
          #1 9 0 1 1
          #2 5 1 2 0
          #3 7 0 3 2
          #4 6 0 4 1
          #5 5 0 5 0
          #6 10 1 6 0
          #7 11 0 7 1
          #8 15 0 8 5





          share|improve this answer


























          • Thank you so much jasbner. Really appreciated it.

            – Marco Mello
            Nov 13 '18 at 21:39



















          2














          This is the same as @jasbner's except using a rolling join, which I suspect might be more efficient in some cases:



          library(data.table)
          setDT(DF)

          DF[, v := DF[city == 1][.SD, on=.(distance), roll="nearest", abs(x.distance-i.distance)]]

          distance city obs v
          1: 9 0 1 1
          2: 5 1 2 0
          3: 7 0 3 2
          4: 6 0 4 1
          5: 5 0 5 0
          6: 10 1 6 0
          7: 11 0 7 1
          8: 15 0 8 5





          share|improve this answer



















          • 1





            I think they don't and that this is the current status @jasbner : github.com/tidyverse/dplyr/issues/2240

            – Frank
            Nov 13 '18 at 21:54











          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%2f53289635%2foperation-along-the-same-column-given-a-logical-condition%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









          2














          Here's a dplyr solution where you find the minimum distance to any of the cities:



          library(dplyr)
          df %>% rowwise %>% mutate(difference = min(abs(df$distance[df$city == 1] - distance)))
          #Source: local data frame [8 x 4]
          #Groups: <by row>
          #
          # A tibble: 8 x 4
          # distance city obs difference
          # <int> <int> <int> <int>
          #1 9 0 1 1
          #2 5 1 2 0
          #3 7 0 3 2
          #4 6 0 4 1
          #5 5 0 5 0
          #6 10 1 6 0
          #7 11 0 7 1
          #8 15 0 8 5


          And here is a base-r approach:



          df$difference <- sapply(df$distance,function(x)  min(abs(df$distance[df$city == 1] - x)))
          df
          # distance city obs difference
          #1 9 0 1 1
          #2 5 1 2 0
          #3 7 0 3 2
          #4 6 0 4 1
          #5 5 0 5 0
          #6 10 1 6 0
          #7 11 0 7 1
          #8 15 0 8 5





          share|improve this answer


























          • Thank you so much jasbner. Really appreciated it.

            – Marco Mello
            Nov 13 '18 at 21:39
















          2














          Here's a dplyr solution where you find the minimum distance to any of the cities:



          library(dplyr)
          df %>% rowwise %>% mutate(difference = min(abs(df$distance[df$city == 1] - distance)))
          #Source: local data frame [8 x 4]
          #Groups: <by row>
          #
          # A tibble: 8 x 4
          # distance city obs difference
          # <int> <int> <int> <int>
          #1 9 0 1 1
          #2 5 1 2 0
          #3 7 0 3 2
          #4 6 0 4 1
          #5 5 0 5 0
          #6 10 1 6 0
          #7 11 0 7 1
          #8 15 0 8 5


          And here is a base-r approach:



          df$difference <- sapply(df$distance,function(x)  min(abs(df$distance[df$city == 1] - x)))
          df
          # distance city obs difference
          #1 9 0 1 1
          #2 5 1 2 0
          #3 7 0 3 2
          #4 6 0 4 1
          #5 5 0 5 0
          #6 10 1 6 0
          #7 11 0 7 1
          #8 15 0 8 5





          share|improve this answer


























          • Thank you so much jasbner. Really appreciated it.

            – Marco Mello
            Nov 13 '18 at 21:39














          2












          2








          2







          Here's a dplyr solution where you find the minimum distance to any of the cities:



          library(dplyr)
          df %>% rowwise %>% mutate(difference = min(abs(df$distance[df$city == 1] - distance)))
          #Source: local data frame [8 x 4]
          #Groups: <by row>
          #
          # A tibble: 8 x 4
          # distance city obs difference
          # <int> <int> <int> <int>
          #1 9 0 1 1
          #2 5 1 2 0
          #3 7 0 3 2
          #4 6 0 4 1
          #5 5 0 5 0
          #6 10 1 6 0
          #7 11 0 7 1
          #8 15 0 8 5


          And here is a base-r approach:



          df$difference <- sapply(df$distance,function(x)  min(abs(df$distance[df$city == 1] - x)))
          df
          # distance city obs difference
          #1 9 0 1 1
          #2 5 1 2 0
          #3 7 0 3 2
          #4 6 0 4 1
          #5 5 0 5 0
          #6 10 1 6 0
          #7 11 0 7 1
          #8 15 0 8 5





          share|improve this answer















          Here's a dplyr solution where you find the minimum distance to any of the cities:



          library(dplyr)
          df %>% rowwise %>% mutate(difference = min(abs(df$distance[df$city == 1] - distance)))
          #Source: local data frame [8 x 4]
          #Groups: <by row>
          #
          # A tibble: 8 x 4
          # distance city obs difference
          # <int> <int> <int> <int>
          #1 9 0 1 1
          #2 5 1 2 0
          #3 7 0 3 2
          #4 6 0 4 1
          #5 5 0 5 0
          #6 10 1 6 0
          #7 11 0 7 1
          #8 15 0 8 5


          And here is a base-r approach:



          df$difference <- sapply(df$distance,function(x)  min(abs(df$distance[df$city == 1] - x)))
          df
          # distance city obs difference
          #1 9 0 1 1
          #2 5 1 2 0
          #3 7 0 3 2
          #4 6 0 4 1
          #5 5 0 5 0
          #6 10 1 6 0
          #7 11 0 7 1
          #8 15 0 8 5






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 13 '18 at 21:43

























          answered Nov 13 '18 at 21:36









          jasbnerjasbner

          2,026618




          2,026618













          • Thank you so much jasbner. Really appreciated it.

            – Marco Mello
            Nov 13 '18 at 21:39



















          • Thank you so much jasbner. Really appreciated it.

            – Marco Mello
            Nov 13 '18 at 21:39

















          Thank you so much jasbner. Really appreciated it.

          – Marco Mello
          Nov 13 '18 at 21:39





          Thank you so much jasbner. Really appreciated it.

          – Marco Mello
          Nov 13 '18 at 21:39













          2














          This is the same as @jasbner's except using a rolling join, which I suspect might be more efficient in some cases:



          library(data.table)
          setDT(DF)

          DF[, v := DF[city == 1][.SD, on=.(distance), roll="nearest", abs(x.distance-i.distance)]]

          distance city obs v
          1: 9 0 1 1
          2: 5 1 2 0
          3: 7 0 3 2
          4: 6 0 4 1
          5: 5 0 5 0
          6: 10 1 6 0
          7: 11 0 7 1
          8: 15 0 8 5





          share|improve this answer



















          • 1





            I think they don't and that this is the current status @jasbner : github.com/tidyverse/dplyr/issues/2240

            – Frank
            Nov 13 '18 at 21:54
















          2














          This is the same as @jasbner's except using a rolling join, which I suspect might be more efficient in some cases:



          library(data.table)
          setDT(DF)

          DF[, v := DF[city == 1][.SD, on=.(distance), roll="nearest", abs(x.distance-i.distance)]]

          distance city obs v
          1: 9 0 1 1
          2: 5 1 2 0
          3: 7 0 3 2
          4: 6 0 4 1
          5: 5 0 5 0
          6: 10 1 6 0
          7: 11 0 7 1
          8: 15 0 8 5





          share|improve this answer



















          • 1





            I think they don't and that this is the current status @jasbner : github.com/tidyverse/dplyr/issues/2240

            – Frank
            Nov 13 '18 at 21:54














          2












          2








          2







          This is the same as @jasbner's except using a rolling join, which I suspect might be more efficient in some cases:



          library(data.table)
          setDT(DF)

          DF[, v := DF[city == 1][.SD, on=.(distance), roll="nearest", abs(x.distance-i.distance)]]

          distance city obs v
          1: 9 0 1 1
          2: 5 1 2 0
          3: 7 0 3 2
          4: 6 0 4 1
          5: 5 0 5 0
          6: 10 1 6 0
          7: 11 0 7 1
          8: 15 0 8 5





          share|improve this answer













          This is the same as @jasbner's except using a rolling join, which I suspect might be more efficient in some cases:



          library(data.table)
          setDT(DF)

          DF[, v := DF[city == 1][.SD, on=.(distance), roll="nearest", abs(x.distance-i.distance)]]

          distance city obs v
          1: 9 0 1 1
          2: 5 1 2 0
          3: 7 0 3 2
          4: 6 0 4 1
          5: 5 0 5 0
          6: 10 1 6 0
          7: 11 0 7 1
          8: 15 0 8 5






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 13 '18 at 21:47









          FrankFrank

          54.1k654128




          54.1k654128








          • 1





            I think they don't and that this is the current status @jasbner : github.com/tidyverse/dplyr/issues/2240

            – Frank
            Nov 13 '18 at 21:54














          • 1





            I think they don't and that this is the current status @jasbner : github.com/tidyverse/dplyr/issues/2240

            – Frank
            Nov 13 '18 at 21:54








          1




          1





          I think they don't and that this is the current status @jasbner : github.com/tidyverse/dplyr/issues/2240

          – Frank
          Nov 13 '18 at 21:54





          I think they don't and that this is the current status @jasbner : github.com/tidyverse/dplyr/issues/2240

          – Frank
          Nov 13 '18 at 21:54


















          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%2f53289635%2foperation-along-the-same-column-given-a-logical-condition%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

          Bressuire

          Vorschmack

          Quarantine