0

enter image description here

Here's what I have, but I don't think it's right:

gas.test <- data.frame(gas=c(0, 14, 12, 13, 11, 17, 0, 13, 11, 10, 14, 14, 0,
                             12, 12, 13, 13, 12, 0, 11, 12, 10, 9, 8, 0),
                       Test_Car = factor(rep(c("A", "B", "C", "D", "E"), each=5)),
                       Additive = factor(rep(c(1, 2, 3, 4, 5), 5)))
kangaroo_cliff
  • 6,067
  • 3
  • 29
  • 42
mr.A
  • 1
  • 1
  • 2
    Is the expected output `gas.test`? Can you show the `dput(input_data)` Have you tried `as.data.frame(input_data)` – akrun Nov 29 '20 at 22:25
  • 1
    If you have table object, and wants to convert that as is data.frame `as.data.frame.matrix(input_data)` – akrun Nov 29 '20 at 22:31
  • Check https://stackoverflow.com/questions/5890584/how-to-reshape-data-from-long-to-wide-format and https://stackoverflow.com/questions/2185252/reshaping-data-frame-from-wide-to-long-format for general reshaping techniques. – Ronak Shah Nov 30 '20 at 02:32

1 Answers1

1

I am guessing you are after either getting the matrix out of gas.test or the other way around.

Here are both options, using pivot_wider and pivot_longer.

library(tidyr)
gas.test %>%
        pivot_wider(names_from = Test_Car, values_from = gas)
# A tibble: 5 x 6
  Additive     A     B     C     D     E
  <fct>    <dbl> <dbl> <dbl> <dbl> <dbl>
1 1            0    17    14    13    12
2 2           14     0    14    13    10
3 3           12    13     0    12     9
4 4           13    11    12     0     8
5 5           11    10    12    11     0
 mat %>% pivot_longer(!Additive, names_to = "Test_Cars", values_to = "gas")
# A tibble: 25 x 3
   Additive Test_Cars   gas
   <fct>    <chr>     <dbl>
 1 1        A             0
 2 1        B            17
 3 1        C            14
 4 1        D            13
 5 1        E            12

using spread and gather functions.

mat <- gas.test %>% spread(key = Test_Car, value = gas)

gas.test <- mat %>% gather(key = Test_Car, value = gas, -Additive)
kangaroo_cliff
  • 6,067
  • 3
  • 29
  • 42
  • 1
    Better to use `pivot_wider` and `pivot_longer` (as of September 2019's `tidyr 1.0.0` update) instead of `spread` and `gather`. `spread` and `gather` are officially retired (see `vignette("pivot")` for more details). – Maurits Evers Nov 30 '20 at 01:53
  • 1
    Cheers. Thanks for the info. Hope I've used them correctly here. – kangaroo_cliff Nov 30 '20 at 02:18