df_transpose Function

public function df_transpose(df) result(transposed_df)

Transpose a data frame

Creates a transposed data frame where rows become columns and columns become rows. Note: All data is converted to character type in the transposed frame.

@param[in] df The source data frame @return transposed_df New data frame that is the transpose of the source

Arguments

Type IntentOptional Attributes Name
type(data_frame), intent(in) :: df

Return Value type(data_frame)


Source Code

    function df_transpose(df) result(transposed_df)
        type(data_frame), intent(in) :: df
        type(data_frame) :: transposed_df

        integer :: i, j
        character(len=:), dimension(:), allocatable :: row_data
        character(len=20) :: temp_str
        type(column) :: col

        call transposed_df % new()

        ! Add headers as first column if present
        if (df % get_with_headers()) then
            allocate (character(len=df % get_max_char_len()) :: row_data(df % ncols()))
            do i = 1, df % ncols()
                row_data(i) = df % header(i)
            end do
            call df_append_character(transposed_df, row_data, "Headers")
            deallocate (row_data)
        end if

        ! Add each row as a column
        do i = 1, df % nrows()
            allocate (character(len=50) :: row_data(df % ncols()))

            do j = 1, df % ncols()
                col = df % get_data_col(j)

                select case (col % get_type())
                case (REAL_NUM)
                    write (temp_str, '(f0.6)') col % getr(i)
                    row_data(j) = trim(temp_str)
                case (INTEGER_NUM)
                    write (temp_str, '(i0)') col % geti(i)
                    row_data(j) = trim(temp_str)
                case (LOGICAL_NUM)
                    if (col % getl(i)) then
                        row_data(j) = "T"
                    else
                        row_data(j) = "F"
                    end if
                case (CHARACTER_NUM)
                    row_data(j) = col % getch(i)
                case (COMPLEX_NUM)
                    write (temp_str, '("(",f0.3,",",f0.3,")")') col % getc(i)
                    row_data(j) = trim(temp_str)
                end select
            end do

            write (temp_str, '("Row_",i0)') i
            call df_append_character(transposed_df, row_data, trim(temp_str))
            deallocate (row_data)
        end do
    end function df_transpose