-2

I am just looking for a way in R to re-allocate the data of a file. I have multiple columns and I want to store them all under one column with another one next to that indicates the column name, For example:

I have this:

A    B    C
a1   b1   c1
a2   b2   c2

And I would like to make something like that:

Item   Label

 a1     A
 a2     A
 b1     B
 b2     B
 c1     C
 c2     C

(Ideally, I'd like to do that for multiple columns. Thus, I suppose this could be done with a for command).

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213

1 Answers1

0

Read the excel-data to R with your favourite excel-parser (I usually use the readxl-package for this), then reshape the data (see below for code) and write the result back to excel (for example with the openxlsx-package).

library(data.table)
dt <- fread("A    B    C
a1   b1   c1
a2   b2   c2")

melt(dt, measure.vars = names(dt), variable.name = "Item", value.name = "Label")

#    Item Label
# 1:    A    a1
# 2:    A    a2
# 3:    B    b1
# 4:    B    b2
# 5:    C    c1
# 6:    C    c2
Wimpel
  • 26,031
  • 1
  • 20
  • 37