Jonathan1234
Jonathan1234

Reputation: 499

Bring Tibble into Data Frame form with columns as row and column index

I have the following tibble data frame in R

tribble(
  ~x, ~y,  ~z,
  "a", "A1",  3.6,
  "b", "A2",  8.5,
  "c", "A1",  4.6,
  "d", "A2",  6.5,
  "e", "A1",  1.6,
  "f", "A2",  9.5
)
# A tibble: 6 x 3
  x     y         z
  <chr> <chr> <dbl>
1 a     A1      3.6
2 b     A2      8.5
3 c     A1      4.6
4 d     A2      6.5
5 e     A1      1.6
6 f     A2      9.5

Is there a way to bring the tibble into the following form

     a   b   c   d   e   f
A1 3.6 4.6 1.6 8.5 6.5 9.5
A2 3.6 4.6 1.6 8.5 6.5 9.5

Upvotes: 1

Views: 119

Answers (2)

akrun
akrun

Reputation: 887891

We can use

library(dplyr)
library(tidyr)
df %>%
    pivot_wider(names_from = x, values_from = z) %>%    
    mutate(across(where(is.numeric), ~ .[!is.na(.)]))
# A tibble: 2 x 7
  y         a     b     c     d     e     f
  <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 A1      3.6   8.5   4.6   6.5   1.6   9.5
2 A2      3.6   8.5   4.6   6.5   1.6   9.5

Upvotes: 2

Ronak Shah
Ronak Shah

Reputation: 389275

Get the data in wide format and fill the NA values -

library(dplyr)
library(tidyr)

df %>%
  pivot_wider(names_from = x, values_from = z) %>%
  fill(everything(), .direction = 'downup')

#   y       a     b     c     d     e     f
#  <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#1 A1      3.6   8.5   4.6   6.5   1.6   9.5
#2 A2      3.6   8.5   4.6   6.5   1.6   9.5

Upvotes: 2

Related Questions