Henryk Borzymowski
Henryk Borzymowski

Reputation: 1078

Matching of positive to negative numbers in the same group - R

I would like to do the following thing:

id calendar_week value
1    1              10
2    2              2
3    2             -2
4    2              3
5    3              10 
6    3             -10

The output which I want is the list of id (or the rows) which have a positiv to negative match for a given calendar_week -> which means I want for example the id 2 and 3 because there is a match of -2 to 2 in Calendar week 2. I don't want id 4 because there is no -3 value in calendar week 2 and so on.

output:

id calendar_week value 
2    2              2
3    2             -2
5    3              10 
6    3             -10

Upvotes: 0

Views: 537

Answers (3)

arg0naut91
arg0naut91

Reputation: 14764

Could also do:

library(dplyr)

df %>%
  group_by(calendar_week, ab = abs(value)) %>%
  filter(n() > 1) %>% ungroup() %>%
  select(-ab)

Output:

# A tibble: 4 x 3
     id calendar_week value
  <int>         <int> <int>
1     2             2     2
2     3             2    -2
3     5             3    10
4     6             3   -10

Given your additional clarifications, you could do:

df %>%
  group_by(calendar_week, value) %>%
  mutate(idx = row_number()) %>%
  group_by(calendar_week, idx, ab = abs(value)) %>%
  filter(n() > 1) %>% ungroup() %>%
  select(-idx, -ab)

On a modified data frame:

  id calendar_week value
1  1             1    10
2  2             2     2
3  3             2    -2
4  3             2     2
5  4             2     3
6  5             3    10
7  6             3   -10
8  7             4    10
9  8             4    10

This gives:

# A tibble: 4 x 3
     id calendar_week value
  <int>         <int> <int>
1     2             2     2
2     3             2    -2
3     5             3    10
4     6             3   -10

Upvotes: 2

lroha
lroha

Reputation: 34441

If as stated in the comments only a single match is required you could try:

library(dplyr)

df %>%
  group_by(calendar_week, nvalue = abs(value)) %>% 
  filter(!duplicated(value)) %>%
  filter(sum(value) == 0) %>% 
  ungroup() %>%
  select(-nvalue)

     id calendar_week value
  <int>         <int> <int>
1     2             2     2
2     3             2    -2
3     5             3   -10
4     6             3    10

Upvotes: 1

Paweł Chabros
Paweł Chabros

Reputation: 2399

Using tidyverse :

library(tidyverse)

df %>%
  group_by(calendar_week) %>%
  nest() %>%
  mutate(values = map_chr(data, ~ str_c(.x$value, collapse = ', '))) %>%
  unnest() %>%
  filter(str_detect(values, as.character(-value))) %>%
  select(-values)

Output :

calendar_week    id value
          <dbl> <int> <dbl>
1             2     2     2
2             2     3    -2
3             3     5    10
4             3     6   -10

Upvotes: 1

Related Questions