sirox84
October 25, 2020, 12:39am
1
Hi all,
I would like to know if it will be possible to spread my dataframe specifying rows for a specific column.
Every 3 rows i would like to spread my dataframe for all my columns and append a spread of the next 3 rows.
An example could be:
name of database: MODEL
ID A B C
ESF_Beta 1 4 9
ESF_Gamma 5 5 5
ESF_Alfa 7 9 1
GIN_Beta 3 2 8
GIN_Gamma 4 8 3
GIN_Alfa 2 1 7
Results dataframe:
ID A_Beta A_Gamma A_Alfa B_Beta B_Gamma B_Alfa C_Beta C_Gamma C_Alfa
ESF 1 5 7 4 5 9 9 5 1
GIN 3 4 2 2 8 1 8 3 7
Thanks a lot
FJCC
October 25, 2020, 2:05am
2
Try the pivot_wider() function from the tidyr package.
DF <- read.csv("~/R/Play/Dummy.csv")
DF
#> ID A B C
#> 1 ESF_Beta 1 4 9
#> 2 ESF_Gamma 5 5 5
#> 3 ESF_Alfa 7 9 1
#> 4 GIN_Beta 3 2 8
#> 5 GIN_Gamma 4 8 3
#> 6 GIN_Alfa 2 1 7
library(tidyr)
DF <- DF %>% separate(ID,into = c("ID","Label"))
DF
#> ID Label A B C
#> 1 ESF Beta 1 4 9
#> 2 ESF Gamma 5 5 5
#> 3 ESF Alfa 7 9 1
#> 4 GIN Beta 3 2 8
#> 5 GIN Gamma 4 8 3
#> 6 GIN Alfa 2 1 7
pivot_wider(DF,names_from = Label,values_from = c("A","B","C"))
#> # A tibble: 2 x 10
#> ID A_Beta A_Gamma A_Alfa B_Beta B_Gamma B_Alfa C_Beta C_Gamma C_Alfa
#> <chr> <int> <int> <int> <int> <int> <int> <int> <int> <int>
#> 1 ESF 1 5 7 4 5 9 9 5 1
#> 2 GIN 3 4 2 2 8 1 8 3 7
Created on 2020-10-24 by the reprex package (v0.3.0)
FJCC:
pivot_wider(DF,names_from = Label,values_from = c("A","B","C"))
Thanks man,
Exactly it is what I was looking for.
Perfect solution with pivot_wider.
Thank you very much.
system
Closed
November 1, 2020, 7:21pm
4
This topic was automatically closed 7 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.