rdataframetranspose

Transpose a dataframe maintaining the first column as heading


I have a big dataframe, but small example would be like this:

mydf <- data.frame(A = c(letters[1:10]), M1 = c(11:20), M2 = c(31:40), M3 = c(41:50))

#    A M1 M2 M3
#  1 a 11 31 41
#  2 b 12 32 42
#  3 c 13 33 43
#  4 d 14 34 44
#  5 e 15 35 45
#  6 f 16 36 46
#  7 g 17 37 47
#  8 h 18 38 48
#  9 i 19 39 49
# 10 j 20 40 50

I want to transpose the dataframe and maintain the column 1 (A) as column heading ( letter[1:10]) as variable names. The following are scratch trials of unsuccessful codes.

tmydf = data.frame(t(mydf))
names(tmydf) <- tmydf[1,]

Solution

  • Here is one way, transpose excluding 1st column, then use the 1st column to set the column names:

    tmydf <- setNames(data.frame(t(mydf[,-1])), mydf[,1])
    
    #     a  b  c  d  e  f  g  h  i  j
    # M1 11 12 13 14 15 16 17 18 19 20
    # M2 31 32 33 34 35 36 37 38 39 40
    # M3 41 42 43 44 45 46 47 48 49 50