0

I am trying to figure out a quick way to pivot this table. My input table is like this

+------+------+------+
| FY   | col1 | col2 |
+------+------+------+
| 2019 | 34   | 28   |
+------+------+------+
| 2018 | 22   | 39   |
+------+------+------+

and I want my output table to be

+-----------+-----------+-----------+-----------+
| col1.2018 | col1.2019 | col2.2018 | col2.2018 |
+-----------+-----------+-----------+-----------+
| 22        | 34        | 39        | 28        |
+-----------+-----------+-----------+-----------+

What is the most quick way to do it? I tries using reshape and tidyr but I am not getting the output desired. Any guidance or direction is appreciated

Edit: This is not an exact duplication of other question as pointed out. Although its similar, but not same

arin
  • 61
  • 8

1 Answers1

-1

An option would be to gather the columns ('col1', 'col2') to long format with gather), unite the 'key' with 'FY' column and then spread back to 'wide' format

library(tidyverse)
gather(df1, key, val, col1:col2) %>%
     unite(key1, key, FY, sep=".") %>%
     spread(key1, val)
#   col1.2018 col1.2019 col2.2018 col2.2019
#1        22        34        39        28

data

df1 <- structure(list(FY = c(2019, 2018), col1 = c(34, 22), col2 = c(28, 
 39)), class = "data.frame", row.names = c(NA, -2L))
akrun
  • 874,273
  • 37
  • 540
  • 662
  • 1
    superquick.. good lord thank you so much.. I will accept your solution in next 8 mins.. :) – arin May 17 '19 at 20:47