Sometimes it's very useful to be able to swap rows and columns in a tibble. This can be done "manually," as shown in the very clever post by @dromano in this thread.
I've written a function (below) to do the transpose automagically. Any comments of suggestions would be much appreciated.
transpose_tibble <- function(input_tibble, name_of_first_column = NULL){
# This function exchanges rows and columns of a tibble
# AU: Dick Startz
if (! ("tibble" %in% (.packages()))) stop("library tibble must be loaded")
if (!is_tibble(input_tibble)) stop("Input to transpose_tibble must be a tibble")
if ((!is.null(name_of_first_column)) & !is.character(name_of_first_column))
stop("name_of_first_column in transpose_tibble must be character or omitted")
output_tibble <- as_tibble(t(input_tibble), .name_repair = "universal")
# take what were column names of input_tibble and make first column of
# output_tibble
output_tibble <- output_tibble |> add_column(colnames(input_tibble), .before = 1)
# now take what was the first column of input_tibble and use for column names
# substitute name_of_first_column if specified
if (is.null(name_of_first_column))
new_col_names <- output_tibble[1,]
else
new_col_names <- c(name_of_first_column, output_tibble[1, 2:ncol(output_tibble)])
colnames(output_tibble) <- new_col_names
# remove redundant 1st row now being used for column names
output_tibble <- output_tibble |> slice(-1)
}