In R , data.table library dcast() can transform dataset from wide to long shape ,how can i do this in googlespreadsheet?
From this format :
| JAN | FEB | MAR
----------+------------+------------+-----------
Product 1 | 1 | 2 | 3
Product 2 | 4 | 5 | 6
Product 3 | 7 | 8 | 9
Convert it to this format:
Date| Product | Qty
-----------+-----------+----
JAN | Product 1 | 1
FEB | Product 2 | 4
MAR | Product 3 | 9
JAN | Product 2 | 4
FEB | Product 1 | 2
JAN | Product 3 | 7
MAR | Product 2 | 6
FEB | Product 3 | 8
MAR | Product 1 | 3
Do we have any solution to achieve this ?
How about this sample script?
When you use this script, at first, please put the input values to the cells "A1:D4", and run myFunction()
.
function myFunction() {
var sheet = SpreadsheetApp.getActiveSheet();
var values = sheet.getRange("A1:D4").getValues(); // Retrieve values
var result = [];
for (var i = 1; i < values.length; i++) {
for (var j = 1; j < values[i].length; j++) {
result.push([values[0][i], values[j][0], values[j][i]]);
}
}
sheet.getRange("A6:C14").setValues(result); // Put result
}
When result.push([values[0][i], values[j][0], values[j][i]]);
is modified to temp.push([values[0][j], values[i][0], values[i][j]]);
, the following result is obtained.