rawats1
September 2, 2020, 7:08am
1
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
Sanjmeh
September 2, 2020, 9:35am
2
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
rawats1
September 3, 2020, 4:45am
4
Thank you.
I have used subset fn to first convert my semi tall data to tall and then used wider fn
I'll give try with melt and dcast.
rawats1
September 3, 2020, 4:48am
5
It worked as well
Thank you so much.
1 Like
system
Closed
September 24, 2020, 4:48am
6
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.