0

I am currently working with a data frame in R that is a "horizontal" structure. Here is a sample of the data being referred to:

head(all[,1:4])
Variable Channel TIMEPERIOD        Volume
V1      Retail      41640          50
V1      Retail      41671          60
V1      Retail      41699          40
V1      Retail      41730          30
V1      Retail      41760          30
V1      Retail      41791          40

In the above data, the 'Volume' variable is the first of about 50 additional variables/columns in the data frame. My expected output would be:

head(all[,1:5])
Variable Channel TIMEPERIOD  Variable       Value
V1      Retail      41640    Volume         50
V1      Retail      41671    Volume         60
V1      Retail      41699    Volume         40
V1      Retail      41730    Volume         30
V1      Retail      41760    Volume         30
V1      Retail      41791    Volume         40

Is there a quicker way of doing this transformation than inserting a blank variable column and going through the data frame manually column by column? I've done this in the past with:

# Create subset of specific columns
volume <- subset(nielsen_retail, select = c("X__1", "X__2", 
"X__3"))
# Rename columns
colnames(volume) <- c("prod_name", "time_period", "value")
# Insert channel column
volume$channel <- "retail"
# Insert variable column
volume$variable <- "sales_volume"
# Reorder columns
volume <- volume[ , c("prod_name","time_period", 
"channel","variable", "value")]

As you can see, this results in a very manual and time-consuming process in a large data frame. Thanks in advance for your help!

Franchise
  • 1,081
  • 3
  • 15
  • 30

0 Answers0