Transposing Data

Hello, I have a simple data set as follows:

df = data.frame(letters = c("a","a","b","b","c","c"),
bin = rep(c("cat1","cat2"),3),
num1 = c(1:6),
num2 = c(7:12))

I need to transpose (kind of rotation data 90 degrees clockwise) it from long to wide , and having something similar as below:
col_to_row a1 a2 b1 b2 c1 c2
1 letters a a b b c c
2 bin cat1 cat2 cat1 cat2 cat1 cat2
3 num1 1 2 3 4 5 6
4 num2 7 8 9 10 11 12

I tried to use dplyr and tidyverse function but could not get there.
I would have appreciated any suggestion.
Thank you.

In your end result, column a1 through c2 contain a mix of strings and integers. In a data frame, each column has to contain a single type of object (all strings, all integers, ...). Are you willing to have the integers converted to strings (e.g., 2 -> "2")?

Hello,
Yes, that is ok , after I achieve this shape I am going to fix formatting.
Thank you.

Could you say a little about why you need to transpose the table?

Try the following.

library(dplyr)
df2 <- df |> t() |> as.data.frame()
colnames(df2) <- c("a1", "a2", "b1", "b2", "c1", "c2")
df2 <- df2 |> mutate(col_to_row = rownames(df2)) |> relocate(col_to_row)
rownames(df2) <- NULL

Hello,
Your code works great.
Thank you.

This topic was automatically closed 90 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.