Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature Request: Intuitive DataFrame Transposition Functionality in dplyr #6958

Open
hsalberti opened this issue Nov 8, 2023 · 1 comment

Comments

@hsalberti
Copy link

hsalberti commented Nov 8, 2023

Brief description of the problem:

Transposing a DataFrame in dplyr currently requires a combination of pivot_longer() and pivot_wider() functions. This process is not as straightforward as using the base R t() function and can be confusing for users, especially those new to dplyr or coming from a base R background. An intuitive, one-step transposition function would greatly simplify the data manipulation process in dplyr.

Expected output:

A new function, possibly named transpose_df(), that allows users to transpose a DataFrame in a single step, mirroring the simplicity and ease of use of the base R t() function.


library(dplyr)
library(tidyr)

Sample dataframe

df <- tibble::tibble(
x = 1:3,
y = 4:6,
z = 7:9
)

Current method for transposing in dplyr/tidyr

transposed_df <- df %>%
pivot_longer(cols = everything(), names_to = "variable", values_to = "value") %>%
pivot_wider(names_from = "variable", values_from = "value")

Print the transposed dataframe

print(transposed_df)

@philibe
Copy link

philibe commented Nov 8, 2023

Your example doesn't work.

This works:

  • transposed_df <- data.frame(t(df),row.names = names(df))
  • or transposed_df <- df %>% t %>% data.frame(row.names = names(df))
print(transposed_df)

  X1 X2 X3
x  1  2  3
y  4  5  6
z  7  8  9

And setNames (transposed_df ,c("a","b","c")) (or setNames (transposed_df ,paste0("col",1:nrow(df))))

  a b c
x 1 2 3
y 4 5 6
z 7 8 9

  col1 col2 col3
x    1    2    3
y    4    5    6
z    7    8    9

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants