Tabular data objects in R can be easily transposed with t() function. In the following example, we create a matrix of 2 rows and 3 columns, then transpose it, and the rows and columns are interchanged.
#vectors for matrix elements and row names and column names
items <- c(11, 22, 33, 55,66,77)
rn <- c("r1", "r2")
cn <- c("c1", "c2","c3")
#create a 2 × 3 matrix filled by rows
mtx1 <- matrix(items,
nrow = 2, ncol = 3, byrow = TRUE,
dimnames = list(rn, cn))
#show matrix
mtx1
#output
c1 c2 c3
r1 11 22 33
r2 55 66 77
#transpose the matrix and result is printed out
t(mtx1)
#output
r1 r2
c1 11 55
c2 22 66
c3 33 77
In the next example, we create a data frame first, then rows and columns are interchanged with t() function.
#vectors are created
Idnumber <- c(3, 4, 5, 6)
age <- c(76, 32, 64, 22)
gene <- c("T5", "T6", "T5", "T4")
score <- c("Weak", "good", "brilliant", "bad")
#create a data frame
tdata <- data.frame(Idnumber, age, gene, score)
#show data frame
tdata
#output
Idnumber age gene score
1 3 76 T5 Weak
2 4 32 T6 good
3 5 64 T5 brilliant
4 6 22 T4 bad
#show the transposed data frame
t(tdata)
#output
[,1] [,2] [,3] [,4]
Idnumber "3" "4" "5" "6"
age "76" "32" "64" "22"
gene "T5" "T6" "T5" "T4"
score "Weak" "good" "brilliant" "bad"
0 Comments