This function takes a data frame or matrix and flips its rows and columns, effectively transposing the data. Optionally, it can include row names in the resulting data frame.

flip(x, rownames = NULL)

Arguments

x

A data frame or matrix to be flipped.

rownames

Logical or string. If TRUE, row names will be included as the first column. If character, the column will be named respectively.

Value

A data frame with flipped rows and columns. If rownames is TRUE, row names (if x is a matrix) or the first column will contain the original row names (if x is a data frame).

See also

t for transposing matrices and data frames.

Examples

# Create a sample data frame
df <- data.frame(
  Car = c("BMW", "Volvo", "Honda"), 
  Cost = (1:3)*10000, 
  Speed = c(140, 160, 180), 
  Colour = c("Red", "Blue", "Brown")
)

# Flip the data frame
flip(df)
#>      Car   BMW Volvo Honda
#> 1   Cost 10000 20000 30000
#> 2  Speed   140   160   180
#> 3 Colour   Red  Blue Brown

flip(df) |> nice_table()
Car
BMW Volvo Honda
Cost 10000 20000 30000
Speed 140 160 180
Colour Red Blue Brown
# Flip the data frame with row names included flip(df, rownames = TRUE) #> 1 2 3 #> 1 Car BMW Volvo Honda #> 2 Cost 10000 20000 30000 #> 3 Speed 140 160 180 #> 4 Colour Red Blue Brown