Change data from long to wide

Hi Guys,
How to reshape my data from long to wide using Pivot wide in R.

I would like to change my dataset from

date Countries Set 1 Set 2 Set 3
20/01/2018 Europe 6 1 5
20/01/2018 US 0 3 3
25/01/2020 Europe 1 1 2
25/01/2018 US 0 3 6
27/01/2018 Europe 4 3 4
27/01/2018 US 2 1 1

to

Date Europe Set 1 US Set 1 Europe Set 2 US Set 2 Europe Set 3 US Set 3
20/01/2018 6 0 1 3 5 3
25/01/2018 1 0 1 3 2 6
27/01/2018 4 2 3 1 4 1

Many thanks :slight_smile:

Your tall data is actually also wide.
So you have to first melt the semi tall (or wide) to a full tall table using melt and then use dcast to make it as wide as you want.

If your dataframe is not in a datatable format convert it first to data.table:

library(data.table)
setDT(dt1) # where dt1 is your original dataframe.

The data.table can now be quickly transformed to the output you need:

dt2 <- melt(dt1,id.var="date")
dcast(dt2,date ~ variable)
1 Like

the library(tidyverse) way

example_df <- function(intext) {
tf <- tempfile()
writeLines(intext, con = tf)
require(tidyverse)
as_tibble(read.delim(tf))
}
(df <- example_df("
date	Countries	Set1	Set2	Set3
20/01/2018	Europe	6	1	5
20/01/2018	US	0	3	3
25/01/2020	Europe	1	1	2
25/01/2018	US	0	3	6
27/01/2018	Europe	4	3	4
27/01/2018	US	2	1	1"))

(df2 <- pivot_longer(df,cols=Set1:Set3,
                     names_to = "set",
                     values_to="value"))

(df3 <- pivot_wider(df2,
                    names_from=c(Countries,set)))
1 Like

Thank you.
I have used subset fn to first convert my semi tall data to tall and then used wider fn :slight_smile:
I'll give try with melt and dcast.

It worked as well :+1:t2: :+1:t2:
Thank you so much.

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.