Skip to contents

Calculate the percentage (value divided by sum of values in the column) for each column

Usage

columnwisePercentage(x, default = 0, digits = 1)

Arguments

x

two dimensional numeric data structure

default

default value to be used if the calculated percentage is NA.

digits

number of digits (default: 1) to which the resulting percentages are to be rounded. Set to NA to suppress rounding

Examples

# Create a random matrix of integer values
M1 <- matrix(sample(100, 12), nrow = 4, dimnames = list(LETTERS[1:4], 1:3))

# Introduce some NA
values <- as.numeric(M1)
values[sample(length(values), 3)] <- NA
M2 <- matrix(values, nrow = nrow(M1), dimnames = dimnames(M1))

M1
#>    1  2  3
#> A 45 47 69
#> B 23 31  5
#> C 76 68 24
#> D 63 73 79
columnwisePercentage(M1)
#>      1    2    3
#> A 21.7 21.5 39.0
#> B 11.1 14.2  2.8
#> C 36.7 31.1 13.6
#> D 30.4 33.3 44.6

M2
#>    1  2  3
#> A 45 NA 69
#> B NA 31  5
#> C 76 NA 24
#> D 63 73 79
columnwisePercentage(M2)
#>      1    2    3
#> A 24.5  0.0 39.0
#> B  0.0 29.8  2.8
#> C 41.3  0.0 13.6
#> D 34.2 70.2 44.6
columnwisePercentage(M2, default = 0)
#>      1    2    3
#> A 24.5  0.0 39.0
#> B  0.0 29.8  2.8
#> C 41.3  0.0 13.6
#> D 34.2 70.2 44.6