Search code examples
rkableflextable

R Create print table with different types of data in it


Here is my problem

I have this sample data.frame :

Name=c("a","b","c","d")
Value=c(12.3,10.5,2.6,1.2)
Label=c("label1","label2","label3","label4")
df=data.frame(Name,Value,Label)

I want to create a table only for displaying (in a Rnotebook) with the data in df but flipping rows and columns.

wanted displayed table

Is it an efficient way to do it ? flextable or kable do not seem to have flipping possibilities.

A data.frame transposition is not a solution since columns can't mix different data types (numeric, character)...

I can't imagine nobody encountered the problem...


Solution

  • Using a custom function to "flip" your dataframe you could do:

    flip_df <- function(x) {
      x <- data.frame(t(x))
      x <- cbind(row.names(x), x)
      names(x) <- x[1,]
      x[-1, ]  
    }
    
    library(flextable)
    
    flextable(flip_df(df))
    

    enter image description here