Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (5.3k points)
edited by

I need to transpose a large data frame and so I used:

df.aree <- t(df.aree)

df.aree <- as.data.frame(df.aree)

This is what I obtain:

df.aree[c(1:5),c(1:5)]

                         10428        10760        12148        11865

    name                M231T3       M961T5       M960T6      M231T19

    GS04.A        5.847557e+03 0.000000e+00 3.165891e+04 2.119232e+04

    GS16.A        5.248690e+04 4.047780e+03 3.763850e+04 1.187454e+04

    GS20.A        5.370910e+03 9.518396e+03 3.552036e+04 1.497956e+04

    GS40.A        3.640794e+03 1.084391e+04 4.651735e+04 4.120606e+04    

My problem is the new column names(10428, 10760, 12148, 11865) that I need to eliminate because I need to use the first row as column names.

I tried with col.names() function but I haven't obtained what I need.

Do you have any suggestions?

1 Answer

0 votes
by
edited by

To transpose a data frame that includes a string column, you can transpose the numeric columns separately, and then factor the rownames to keep them as column names.

In your case:

# first keep the  rownames

n <- df.aree$name

# transpose all but the first column (name)

df.aree <- as.data.frame(t(df.aree[,-1]))

colnames(df.aree) <- n

df.aree$myfactor <- factor(row.names(df.aree))

For example:

data("mtcars")

n <-rownames(mtcars)

mtcars <- as.data.frame(t(mtcars))

colnames(mtcars) <- n

mtcars$myfac <- factor(row.names(mtcars))

head(mtcars)

Output:

Mazda RX4 Mazda RX4 Wag Datsun 710 Hornet 4 Drive Hornet Sportabout Valiant

mpg      21.00        21.000      22.80         21.400             18.70   18.10

cyl       6.00         6.000       4.00          6.000              8.00    6.00

disp    160.00       160.000     108.00        258.000            360.00  225.00

hp      110.00       110.000      93.00        110.000            175.00  105.00

drat      3.90         3.900       3.85          3.080              3.15    2.76

wt        2.62         2.875       2.32          3.215              3.44    3.46

Browse Categories

...