Skip to contents

This function rotates a data frame, i.e. columns become rows and vice versa. It's the equivalent of using t() but restores the data.frame class, preserves attributes and prints a warning if the data type is modified (see example).

Usage

data_rotate(data, rownames = NULL, colnames = FALSE, verbose = TRUE)

data_transpose(data, rownames = NULL, colnames = FALSE, verbose = TRUE)

Arguments

data

A data frame.

rownames

Character vector (optional). If not NULL, the data frame's rownames will be added as (first) column to the output, with rownames being the name of this column.

colnames

Logical or character vector (optional). If TRUE, the values of the first column in x will be used as column names in the rotated data frame. If a character vector, values from that column are used as column names.

verbose

Toggle warnings.

Value

A (rotated) data frame.

See also

Examples

x <- mtcars[1:3, 1:4]

x
#>                mpg cyl disp  hp
#> Mazda RX4     21.0   6  160 110
#> Mazda RX4 Wag 21.0   6  160 110
#> Datsun 710    22.8   4  108  93

data_rotate(x)
#>      Mazda RX4 Mazda RX4 Wag Datsun 710
#> mpg         21            21       22.8
#> cyl          6             6        4.0
#> disp       160           160      108.0
#> hp         110           110       93.0
data_rotate(x, rownames = "property")
#>   property Mazda RX4 Mazda RX4 Wag Datsun 710
#> 1      mpg        21            21       22.8
#> 2      cyl         6             6        4.0
#> 3     disp       160           160      108.0
#> 4       hp       110           110       93.0

# use values in 1. column as column name
data_rotate(x, colnames = TRUE)
#>       21  21 22.8
#> cyl    6   6    4
#> disp 160 160  108
#> hp   110 110   93
data_rotate(x, rownames = "property", colnames = TRUE)
#>   property  21  21 22.8
#> 1      cyl   6   6    4
#> 2     disp 160 160  108
#> 3       hp 110 110   93

# use either first column or specific column for column names
x <- data.frame(a = 1:5, b = 11:15, c = 21:25)
data_rotate(x, colnames = TRUE)
#>    1  2  3  4  5
#> b 11 12 13 14 15
#> c 21 22 23 24 25
data_rotate(x, colnames = "c")
#>   21 22 23 24 25
#> a  1  2  3  4  5
#> b 11 12 13 14 15