Skip to contents

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

Usage

rowwisePercentage(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 98 40 14
#> B  6 94 67
#> C 51 86 18
#> D 88 72 15
rowwisePercentage(M1)
#>      1    2    3
#> A 64.5 26.3  9.2
#> B  3.6 56.3 40.1
#> C 32.9 55.5 11.6
#> D 50.3 41.1  8.6

M2
#>    1  2  3
#> A 98 40 14
#> B  6 94 67
#> C 51 86 NA
#> D 88 NA NA
rowwisePercentage(M2)
#>       1    2    3
#> A  64.5 26.3  9.2
#> B   3.6 56.3 40.1
#> C  37.2 62.8  0.0
#> D 100.0  0.0  0.0
rowwisePercentage(M2, default = 0)
#>       1    2    3
#> A  64.5 26.3  9.2
#> B   3.6 56.3 40.1
#> C  37.2 62.8  0.0
#> D 100.0  0.0  0.0