Skip to contents

Replace addmargins with treatment for data.frame

Usage

add_margin(x, name, output = c("normal", "data.frame"), ...)

Arguments

x

either a matrix, an array or a data.frame

name

vector, if x is a data.frame, gives the poistion of what should be considered as names (and so not pass to addmargins).

output

character, gives the type of output, either as.is or a data.frame.

...

arguments that will be used for addmargins

Value

A table, array or data.frame with margins added.

Author

Frédéric Grelot

Examples


add_margin(head(iris), 5)
#>        Sepal.Length Sepal.Width Petal.Length Petal.Width  Sum
#> setosa          5.1         3.5          1.4         0.2 10.2
#> setosa          4.9         3.0          1.4         0.2  9.5
#> setosa          4.7         3.2          1.3         0.2  9.4
#> setosa          4.6         3.1          1.5         0.2  9.4
#> setosa          5.0         3.6          1.4         0.2 10.2
#> setosa          5.4         3.9          1.7         0.4 11.4
#> Sum            29.7        20.3          8.7         1.4 60.1
add_margin(head(iris), 5, "data.frame")
#>     name Sepal.Length Sepal.Width Petal.Length Petal.Width  Sum
#> 1 setosa          5.1         3.5          1.4         0.2 10.2
#> 2 setosa          4.9         3.0          1.4         0.2  9.5
#> 3 setosa          4.7         3.2          1.3         0.2  9.4
#> 4 setosa          4.6         3.1          1.5         0.2  9.4
#> 5 setosa          5.0         3.6          1.4         0.2 10.2
#> 6 setosa          5.4         3.9          1.7         0.4 11.4
#>      Sum         29.7        20.3          8.7         1.4 60.1
add_margin(head(iris), 5, FUN = list("total" = sum))
#> Margins computed over dimensions
#> in the following order:
#> 1: 
#> 2: 
#>        Sepal.Length Sepal.Width Petal.Length Petal.Width total
#> setosa          5.1         3.5          1.4         0.2  10.2
#> setosa          4.9         3.0          1.4         0.2   9.5
#> setosa          4.7         3.2          1.3         0.2   9.4
#> setosa          4.6         3.1          1.5         0.2   9.4
#> setosa          5.0         3.6          1.4         0.2  10.2
#> setosa          5.4         3.9          1.7         0.4  11.4
#> total          29.7        20.3          8.7         1.4  60.1

x = data.frame(
    gender = sample(c("H", "F"), 20, replace = TRUE),
    region = sample(c("east", "west", "south", "north"), 20, replace = TRUE),
    wealth = round(runif(20) * 10000),
    size = round(runif(20) * 50 + 150)
)
add_margin(head(x), 1:2, margin = 1, FUN = list(mean = mean))
#>           wealth size
#> H_north 7697.000  197
#> H_east  9907.000  177
#> H_west  9705.000  177
#> F_west  3892.000  164
#> F_south 4612.000  172
#> H_south 3152.000  169
#> mean    6494.167  176