This function rotates a data frame, i.e. columns become rows and vice versa.

rotate_df(x, rn = NULL, cn = FALSE)

Arguments

x

A data frame.

rn

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

cn

Logical (optional), if TRUE, the values of the first column in x will be used as column names in the rotated data frame.

Value

A (rotated) data frame.

Examples

x <- mtcars[1:3, 1:4]
rotate_df(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
rotate_df(x, rn = "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
rotate_df(x, cn = TRUE)
#>       21  21 22.8
#> cyl    6   6    4
#> disp 160 160  108
#> hp   110 110   93
rotate_df(x, rn = "property", cn = TRUE)
#>   property  21  21 22.8
#> 1      cyl   6   6    4
#> 2     disp 160 160  108
#> 3       hp 110 110   93

# also works on list-results
library(purrr)
#> 
#> Attaching package: ‘purrr’
#> The following object is masked from ‘package:sjmisc’:
#> 
#>     is_empty

dat <- mtcars[1:3, 1:4]
tmp <- purrr::map(dat, function(x) {
  sdev <- stats::sd(x, na.rm = TRUE)
  ulsdev <- mean(x, na.rm = TRUE) + c(-sdev, sdev)
  names(ulsdev) <- c("lower_sd", "upper_sd")
  ulsdev
})
tmp
#> $mpg
#> lower_sd upper_sd 
#> 20.56077 22.63923 
#> 
#> $cyl
#> lower_sd upper_sd 
#> 4.178633 6.488034 
#> 
#> $disp
#> lower_sd upper_sd 
#> 112.6445 172.6889 
#> 
#> $hp
#>  lower_sd  upper_sd 
#>  94.51838 114.14829 
#> 
as.data.frame(tmp)
#>               mpg      cyl     disp        hp
#> lower_sd 20.56077 4.178633 112.6445  94.51838
#> upper_sd 22.63923 6.488034 172.6889 114.14829
rotate_df(tmp)
#>        lower_sd   upper_sd
#> mpg   20.560770  22.639230
#> cyl    4.178633   6.488034
#> disp 112.644453 172.688881
#> hp    94.518379 114.148288

tmp <- purrr::map_df(dat, function(x) {
  sdev <- stats::sd(x, na.rm = TRUE)
  ulsdev <- mean(x, na.rm = TRUE) + c(-sdev, sdev)
  names(ulsdev) <- c("lower_sd", "upper_sd")
  ulsdev
})
tmp
#> # A tibble: 4 × 2
#>   lower_sd upper_sd
#>      <dbl>    <dbl>
#> 1    20.6     22.6 
#> 2     4.18     6.49
#> 3   113.     173.  
#> 4    94.5    114.  
rotate_df(tmp)
#>                V1       V2       V3        V4
#> lower_sd 20.56077 4.178633 112.6445  94.51838
#> upper_sd 22.63923 6.488034 172.6889 114.14829