Tidyverse with unique keys and dual key filling NA based on unique keys

Consider a minimal example:

library(tidyverse)
ex <-tribble(
  ~id, ~property, ~value,
  1,    "A",      9,
  1,    "A",      8,
  1,    "B",      7,
  2,    "A",      6,
  2,    "B",      5
)

My goal is to propagate the property to columns to get this table:

tribble(
  ~id, ~A, ~B,
  1,  9,  7,
  1,  8,  7,
  2,  6,  5
)

Grouping with idand propertyand adding the key closes, but leaves NA:

## almost but not quite
ex %>% 
  group_by(id, property) %>%
  mutate(key = row_number()) %>%
  spread(property, value) %>% 
  select(-key) -> X
X

It gives:

     id     A     B
1     1     9     7
2     1     8    NA
3     2     6     5

I can solve this in a minimal example, dividing the above into each property, dropping the NA and attaching back to id:

inner_join(
  na.omit(select(X, id, A)),
  na.omit(select(X, id, B))
)

but it is clear that this does not generalize to an arbitrary set of properties. Which strategy is tidyversebetter?

NOTE. A few previous questions relate to the first half of this, for example. having built a column keyso that it spreaddoesn’t work, but cannot see something, referring to NAs.

+4
1

fill tidyr:

library(dplyr)
library(tidyr)

ex %>% 
  group_by(id, property) %>%
  mutate(key = row_number()) %>%
  spread(property, value) %>% 
  select(-key) %>%
  group_by(id) %>%
  fill(-id)

:

# A tibble: 3 x 3
# Groups:   id [2]
     id     A     B
  <dbl> <dbl> <dbl>
1     1     9     7
2     1     8     7
3     2     6     5
+5

Source: https://habr.com/ru/post/1689459/


All Articles