0

So I've prepared the following dummy-data with the following code,

whatever <- data.frame(model=c("Nug", "Ste"), A=c(1,2), B=c(3,4), C=c(5,6))

...and thus the following dataframe provided by a screenshot (CBB to figure out Stack Overflow's syntax to create a table format):

Original

So the new dataframe would have 2x3 columns and one row, e.g Nug.A = 1, Ste.A = 2**, Nug.B = 3, Ste.B = 4, Nug.C = 5 and finally Ste.C = 6

I'm sure such a data manipulation function already exists, but I do not know the name to call this transformation, so I couldn't Google it. I'm not asking how to go from wide to long, but rather a long (with not one but multiple columns) to wide.

E_net4
  • 27,810
  • 13
  • 101
  • 139
  • Please use `dput` to show the example instead of images. thanks – akrun Nov 28 '21 at 21:37
  • Does this answer your question? [Reshaping data.frame from wide to long format](https://stackoverflow.com/questions/2185252/reshaping-data-frame-from-wide-to-long-format) – NelsonGon Nov 28 '21 at 21:43
  • Does this answer your question? [Reshape multiple value columns to wide format](https://stackoverflow.com/questions/11608167/reshape-multiple-value-columns-to-wide-format) – camille Nov 29 '21 at 01:39

1 Answers1

2
  1. Bring into long format and then
  2. unite the names (this could be also done by pivot_wider with names_glue (I prefer the former one)
  3. pivot_wider
library(dplyr)
library(tidyr)

df %>% 
  pivot_longer(
    -model
  ) %>% 
  unite(name, c("model", "name"), sep = ".") %>% 
  pivot_wider(
    names_from = name,
    values_from = value
  )

output:

Nug.psill Nug.range Nug.kappa Nug.ang1 Nug.ang2 Nug.ang3 Nug.anis1 Nug.anis2 Ste.psill Ste.range Ste.kappa Ste.ang1 Ste.ang2 Ste.ang3 Ste.anis1 Ste.anis2
      <dbl>     <dbl>     <dbl>    <dbl>    <dbl>    <dbl>     <dbl>     <dbl>     <dbl>     <dbl>     <dbl>    <dbl>    <dbl>    <dbl>     <dbl>     <dbl>
1    0.0416         0         0        0        0        0         1         1     0.251   694955.         5        0        0        0         1         1
> 

data:

df <- structure(list(model = c("Nug", "Ste"), psill = c(0.04157538, 
0.25144774), range = c(0, 694955.1), kappa = c(0L, 5L), ang1 = c(0L, 
0L), ang2 = c(0L, 0L), ang3 = c(0L, 0L), anis1 = c(1L, 1L), anis2 = c(1L, 
1L)), class = "data.frame", row.names = c("1", "2"))
TarJae
  • 72,363
  • 6
  • 19
  • 66