Dr. Mark Gardener
Providing training for:
Tips and Tricks - for R and Excel
On these pages you can find tips, tricks and hints for using both R and Excel. At the end of each tip there are links forwards and backwards as appropriate. There is also an index of R tips and an index of Excel tips.
For most analytical purposes the combination of Excel and R is unbeatable! Excel is great as a data management tool and for preparing data for analysis. You can also use it to get an overview of your data or to make simple (and not so simple) graphs. R is an analytical "swiss army knife" and can carry out a mind-boggling array of analytical routines as well as producing great graphics.
Use t() to rotate a data.frame or a matrix
The result is always a matrix
A table object can also be rotated using t()
Only 2-D objects can be rotated, check using dim()
colnames() and rownames() attributes are preserved
names() attributes are lost
Rotating objects using t()
Two dimensional R objects include data.frame, matrix and table objects. You can transpose the rows and columns using the t() command. Here is a simple data.frame:
> dat = as.data.frame(matrix(1:12, ncol = 4))
You can rotate the data.frame so that the rows become the columns and the columns become the rows. That is, you transpose the rows and columns. You simply use the t() command.
The result of the t() command is always a matrix object.
> dat.t = t(dat)
You can also rotate a matrix object or a table, as long as the table only has 2 dimensions. These items will have rownames() and colnames() elements (even if empty). You can use the dim() command to look at the dimensions of an object.
The HairEyeColor table has more than 2 dimensions and so will not rotate:
However, you can get part of the table (as 2-dimensions):
> HEC = as.table(HairEyeColor[,,1])
Now it can be rotated:
The colnames() and rownames() elements are preserved (but transposed of course), any names() attributes are lost (since the result is a matrix):
> HEC.t = t(HEC) > dimnames(HEC.t) $Eye  "Brown" "Blue" "Hazel" "Green"
$Hair  "Black" "Brown" "Red" "Blond"
|Top||<< Previous tip: Object elements, , double [] and $||>> Next tip: Sending R output to disk files|
|Top||Tips & Tricks Home||Index of R Tips||Index of Excel Tips|
|See my Publications about Excel, R, statistics and data analysis||Courses in R, data analysis, data management and statistics||Visit the R Project website|
See my Publications about statistics and data analysis.
MonogRaphs: random topics in R
Writer's Bloc – my latest writing project includes R scripts
Courses in data analysis, data management and statistics.
My Publications about statistics and data analysis
See my personal pages at GardenersOwn