Creater Cyfire
Creater Cyfire

Reputation: 83

How to merge rows into columns in R?

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.

Upvotes: 0

Views: 104

Answers (1)

TarJae
TarJae

Reputation: 79204

  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"))

Upvotes: 2

Related Questions