I have data that looks something like this
df = data.frame(name=c("A","A","B","B"),
group=c("g1","g2","g1","g2"),
V1=c(10,40,20,30),
V2=c(6,3,1,7))
I want to reshape it to look like this:
df = data.frame(name=c("A", "B"),
V1.g1=c(10,20),
V1.g2=c(40,30),
V2.g1=c(6,1),
V2.g2=c(3,7))
Is it possible to do it with tidyR?
I can do it with reshape
reshape(df, idvar='name', timevar='group', direction='wide')
but is always good to learn something new.
To reshape the dataframe from long to wide in Pandas, we can use Pandas' pd. pivot() method. columns : Column to use to make new frame's columns (e.g., 'Year Month'). values : Column(s) to use for populating new frame's values (e.g., 'Avg.
2.2. spread() turns a pair of key:value columns into a set of tidy columns. To use spread() , pass it the name of a data frame, then the name of the key column in the data frame, and then the name of the value column.
The reshape
code is compact as it works for multiple value columns. Using the same in tidyr
, may need a couple of steps. Convert the 'wide' format to 'long' using gather
so that there will be a single 'Val' column, unite
the 'Var' (from previous step) and 'group' columns to create a single 'VarG' column, and then use spread
to reconvert the 'long' to 'wide' format.
library(tidyr)
gather(df, Var, Val, V1:V2) %>%
unite(VarG, Var, group) %>%
spread(VarG, Val)
# name V1_g1 V1_g2 V2_g1 V2_g2
#1 A 10 40 6 3
#2 B 20 30 1 7
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With