How to calculate proportion in a table

Calculate proportion in a table, To determine the value of each cell in a table as a proportion of all values, use the prop.table() function in R.

The following is the fundamental syntax for this function:

`prop.table(x, margin = NULL)`

where:

x: Name of the table

margin: The division margin (1 = row, 2 = column, default is NULL)

Calculate proportion in a table

With the following matrix in R, the following examples explain how to utilize this function in practice.

Principal Component Analysis in R » finnstats

Let’s start by making a matrix.

`mx <- matrix(5:12, nrow=2)`

view the matrix

```mx
[,1] [,2] [,3] [,4]
[1,]    5    7    9   11
[2,]    6    8   10   12```

Approach 1: Use prop.table with margin = NULL

The following code demonstrates how to divide by prop.table() without setting a margin:

```prop.table(mx)
[,1]      [,2]      [,3]      [,4]
[1,] 0.07352941 0.1029412 0.1323529 0.1617647
[2,] 0.08823529 0.1176471 0.1470588 0.1764706```

The prop.table() function displays each value as a percentage of the total.

The above example total sum is 68

Cell [1, 1] = 5/68 = 0.07352941

Cell [1, 2] = 7/68 = [1] 0.1029412

And so on…

It’s worth noting that the prop.table() output adds up to 1.

Approach 2: Use prop.table with margin = 1

The following code demonstrates how to divide each individual value by the row sums using prop.table() with margin=1.

```prop.table(mx, margin = 1)
[,1]      [,2]      [,3]      [,4]
[1,] 0.1562500 0.2187500 0.2812500 0.3437500
[2,] 0.1666667 0.2222222 0.2777778 0.3333333```

It’s worth noting that the prop.table() output’s values add up to 1.

Approach 3: Use prop.table with margin = 2

The following code demonstrates how to divide each individual value by the column sums using prop.table() with margin=2.

Bubble Chart in R-ggplot & Plotly » (Code & Tutorial) » finnstats

```prop.table(mx, margin = 2)
[,1]      [,2]      [,3]      [,4]
[1,] 0.4545455 0.4666667 0.4736842 0.4782609
[2,] 0.5454545 0.5333333 0.5263158 0.5217391```

The sum of the values in the first column of the original table is 5 + 6 = 11.

The proportion become

Cell [1, 1] = 5/11 = 0.4545455

Cell [2, 1] = 6/11 = 0.5454545

And so on…

It’s worth noting that the prop.table() output’s values add up to 1.