R Programming

How to transpose data objects in R

We provide effective and economically affordable training courses for R and Python, click here for more details and course registration !

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"

For getting more knowledge of R and a preview of our training course, you can watch R tutorial videos on our YouTube channel !

wilsonzhang746

Recent Posts

Download R Course source files

Click here to download R Course source files !

2 months ago

Download Python Course source files

Click here to download Python Course Source Files !

2 months ago

How to create a data frame from nested dictionary with Pandas in Python

For online Python training registration, click here ! Pandas provides flexible ways of generating data…

5 months ago

How to delete columns of a data frame in Python

For online Python training registration, click here ! Data frame is the tabular data object…

5 months ago

Using isin() to check membership of a data frame in Python

Click her for course registration ! When a data frame in Python is created via…

5 months ago

How to assign values to Pandas data frame in Python

We provide affordable online training course(via ZOOM meeting) for Python and R programming at fundamental…

5 months ago