[R] reshape a data frame

Jon BR jonsleepy at gmail.com
Thu Jun 4 00:25:02 CEST 2015


I found the gather function from the tidyr package, which worked nicely:

gather(ex,bcX,value, bc1:bc2)
   gIN group bcX value
1  A_1     A     bc1  1219.79
2  A_2     A     bc1  1486.84
3  A_3     A     bc1  1255.80
4  A_4     A     bc1   941.87
5  B_1     B     bc1   588.19
6  B_2     B     bc1   304.02
7  A_1     A     bc2   319.79
8  A_2     A     bc2   186.84
9  A_3     A     bc2   125.80
10 A_4     A     bc2    94.87
11 B_1     B     bc2  1008.19
12 B_2     B     bc2   314.02

Thanks.





On Wed, Jun 3, 2015 at 5:44 PM, Jon BR <jonsleepy at gmail.com> wrote:

> Hello,
>
> I would like to ask for some advice in reformatting a data frame such as
> the following one:
>
>
> gIN <- c("A_1","A_2","A_3","A_4","B_1","B_2")
> bc1 <- c(1219.79, 1486.84, 1255.80, 941.87, 588.19, 304.02)
> bc2 <- c(319.79, 186.84, 125.80, 94.87, 1008.19, 314.02)
> group <- c("A","A","A","A","B","B")
>
> ex <- data.frame("gIN" = gIN, "bc1" = bc1, "bc2"=bc2, "group" = group)
>
> > ex
>   gIN     bc1     bc2 group
> 1 A_1 1219.79  319.79     A
> 2 A_2 1486.84  186.84     A
> 3 A_3 1255.80  125.80     A
> 4 A_4  941.87   94.87     A
> 5 B_1  588.19 1008.19     B
> 6 B_2  304.02  314.02     B
>
> I would like to reshape this data frame where all the columns that have
> bc1, bc2,...etc are merged into a single column (call it bcX or something)
> and the other variables are kept apart, the example solution follows:
>
>
> > ex_reshaped
>   gIN     bcX     group
> 1 A_1 1219.79       A
> 2 A_2 1486.84       A
> 3 A_3 1255.80       A
> 4 A_4  941.87        A
> 5 B_1  588.19      B
> 6 B_2  304.02       B
> 7 A_1 319.79       A
> 8 A_2 186.84       A
> 9 A_3 125.80       A
> 10 A_4 94.87       A
> 11 B_1 1008.19   B
> 12 B_2 314.02     B
>
> Does anyone know of a package, and/or command to accomplish this?
>
> Thank you
>

	[[alternative HTML version deleted]]



More information about the R-help mailing list