Reverse ROWS to COLUMNS

Hi guys,
sorry for the question, perhaps trivial.

I have to reverse the rows with the columns. i mean i have a dataframe like:

 V1      V2

1 Gender Male
2 Weight 75 kg
3 Height 175 cm
4 Age 21

i would like to get:

Gender Weight Height Age
Male 75kg 175cm 21

This is one way to do it

df <- data.frame(stringsAsFactors = FALSE,
                 V1 = c("Gender", "Weight", "Height", "Age"),
                 V2 = c("Male", "75 kg", "175 cm", "21")
)

rownames(df) <- df$V1
df$V1 <- NULL
df <- as.matrix(df)
df <- as.data.frame(t(df))
rownames(df) <- NULL
df
#>   Gender Weight Height Age
#> 1   Male  75 kg 175 cm  21

Created on 2019-02-07 by the reprex package (v0.2.1)

2 Likes

thanks it's perfect :slight_smile:

You can simply use the transpose of a data frame i.e. t(df) where df is name of your data frame. For more information read https://www.r-statistics.com/tag/transpose/

1 Like

If your question's been answered (even by you!), would you mind choosing a solution? It helps other people see which questions still need help, or find solutions if they have similar problems. Here’s how to do it:

Here's another approach, using spread() from the tidyr package.

library(tidyr)

df <- data.frame(stringsAsFactors = FALSE,
                 V1 = c("Gender", "Weight", "Height", "Age"),
                 V2 = c("Male", "75 kg", "175 cm", "21")
)

df
#>       V1     V2
#> 1 Gender   Male
#> 2 Weight  75 kg
#> 3 Height 175 cm
#> 4    Age     21

spread(df, V1, V2)
#>   Age Gender Height Weight
#> 1  21   Male 175 cm  75 kg

Created on 2019-02-07 by the reprex package (v0.2.1)

2 Likes

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.