rotate_df: Rotate a data frame

Description Usage Arguments Value Examples

View source: R/rotate_df.R

Description

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

Usage

1
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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
x <- mtcars[1:3, 1:4]
rotate_df(x)
rotate_df(x, rn = "property")

# use values in 1. column as column name
rotate_df(x, cn = TRUE)
rotate_df(x, rn = "property", cn = TRUE)

# also works on list-results
library(purrr)

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
as.data.frame(tmp)
rotate_df(tmp)

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
rotate_df(tmp)

Example output

sh: 1: cannot create /dev/null: Permission denied
sh: 1: wc: Permission denied
Could not detect number of cores, defaulting to 1.
     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
  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
      21  21 22.8
cyl    6   6    4
disp 160 160  108
hp   110 110   93
  property  21  21 22.8
1      cyl   6   6    4
2     disp 160 160  108
3       hp 110 110   93

Attaching package: 'purrr'

The following object is masked from 'package:sjmisc':

    is_empty

$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 

              mpg      cyl     disp        hp
lower_sd 20.56077 4.178633 112.6445  94.51838
upper_sd 22.63923 6.488034 172.6889 114.14829
       lower_sd   upper_sd
mpg   20.560770  22.639230
cyl    4.178633   6.488034
disp 112.644453 172.688881
hp    94.518379 114.148288
# A tibble: 2 x 4
    mpg   cyl  disp    hp
  <dbl> <dbl> <dbl> <dbl>
1  20.6  4.18  113.  94.5
2  22.6  6.49  173. 114. 
             V1         V2
mpg   20.560770  22.639230
cyl    4.178633   6.488034
disp 112.644453 172.688881
hp    94.518379 114.148288

sjmisc documentation built on Dec. 11, 2021, 9:34 a.m.