Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

convert dataframe from wide to long in r

I have a dataframe which is like below:

structure(list(A = c(6.53920197406645, 6.12380136266864, 8.01553257692446, 
4.62636832157394, 7.58222133679378), B = c(6.56200038984423, 
6.09642510342734, 7.73715705458708, 4.64560570976, 7.23920390575521
), C = c(6.80800376627205, 7.92368949337286, 8.01633247802198, 
4.87384339969836, 6.83446360366941), D = c(6.69117551163928, 
5.93689715688807, 8.40247900956586, 4.20000164335469, 6.78643597456963
), E = c(6.30449572859692, 5.99369984659008, 7.86273536430256, 
4.11510456695528, 7.11972911832181), eID = c("hsa:5982", "hsa:3310", 
"hsa:7849", "hsa:2978", "hsa:7318")), row.names = c("X1053_at", 
"X117_at", "X121_at", "X1255_g_at", "X1294_at"), class = "data.frame")

I would like to extend this dataframe as in each row I would have:

A X1053_at 6.539202 hsa:5982
B X1053_at 6.562000 hsa:5982

and so on.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How I can do so?

>Solution :

You may try using reshape2::melt

library(dplyr)
library(tibble)

df %>%
  rownames_to_column("something") %>%
  reshape2::melt(id.cols = c(something, eID), variable.name = "a", value.name = "b") %>%
  select(a, something, b, eID)

   a  something        b      eID
1  A   X1053_at 6.539202 hsa:5982
2  A    X117_at 6.123801 hsa:3310
3  A    X121_at 8.015533 hsa:7849
4  A X1255_g_at 4.626368 hsa:2978
5  A   X1294_at 7.582221 hsa:7318
6  B   X1053_at 6.562000 hsa:5982
7  B    X117_at 6.096425 hsa:3310
8  B    X121_at 7.737157 hsa:7849
9  B X1255_g_at 4.645606 hsa:2978
10 B   X1294_at 7.239204 hsa:7318
11 C   X1053_at 6.808004 hsa:5982
12 C    X117_at 7.923689 hsa:3310
13 C    X121_at 8.016332 hsa:7849
14 C X1255_g_at 4.873843 hsa:2978
15 C   X1294_at 6.834464 hsa:7318
16 D   X1053_at 6.691176 hsa:5982
17 D    X117_at 5.936897 hsa:3310
18 D    X121_at 8.402479 hsa:7849
19 D X1255_g_at 4.200002 hsa:2978
20 D   X1294_at 6.786436 hsa:7318
21 E   X1053_at 6.304496 hsa:5982
22 E    X117_at 5.993700 hsa:3310
23 E    X121_at 7.862735 hsa:7849
24 E X1255_g_at 4.115105 hsa:2978
25 E   X1294_at 7.119729 hsa:7318
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading