Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert columns to rows keeping the name of the column

Tags:

dataframe

r

Is there any way in R to Convert columns to rows keeping the name of the column?

Example input:

A   B
1   1
2   3
3   4
44  5

Output

 Group Number
  A       1
  A       2
  A       3
  A       44 
  B       1
  B       3
  B       4
  B       5
like image 758
Demian Asborn Avatar asked Jul 30 '13 13:07

Demian Asborn


People also ask

How do you keep a column name in Excel?

Freeze columns and rows Select the cell below the rows and to the right of the columns you want to keep visible when you scroll. Select View > Freeze Panes > Freeze Panes.

How do I convert column names to rows?

Here's how you can transpose cell content: Copy the cell range. Select the empty cells where you want to paste the transposed data. On the Home tab, click the Paste icon, and select Paste Transpose.


1 Answers

No need to use reshape2, you can use the stack function from base-R :

With your.data as your example:

res <- stack(your.data)
colnames(res) = c("Number", "Group")

gives you

> res
  Number Group
1      1     A
2      2     A
3      3     A
4     44     A
5      1     B
6      3     B
7      4     B
8      5     B

See also here.


Benchmarking melt from reshape2 and stack from base on bigger data:

require(reshape2)
set.seed(45)
DF <- data.frame(matrix(sample(20, 1e6, TRUE), ncol=100))

require(microbenchmark)
microbenchmark(stack(DF), melt(DF), times=100)

Unit: milliseconds
      expr      min       lq   median       uq      max neval
 stack(DF) 157.7084 187.1993 241.8206 251.7132 334.5488   100
  melt(DF) 174.6079 253.1088 261.6234 273.3971 443.9953   100

Seems like stack is faster, but by a margin of 20 milliseconds...

like image 96
user1981275 Avatar answered Nov 09 '22 23:11

user1981275