How is the prop.table function used in the R language?

The prop.table function is used to calculate the frequency or relative frequency of a table (array). It divides each element in the table by the total sum of all elements in the table to determine the relative frequency of each element.

The syntax of the prop.table function is:

prop.table(x, margin = NULL)

Explanation of Parameters:

  1. An object representing a table (array).
  2. The margin parameter specifies the dimension for calculating frequencies. The default value is NULL, indicating frequencies are calculated for the entire table. Setting it to 1 calculates frequencies by rows, while setting it to 2 calculates frequencies by columns.

Return value:

  1. Return an object with the same dimensions as the input table (array), where each element represents the relative frequency.

Suppose there is a table object x, which contains the following data:

x <- array(c(1, 2, 3, 4), dim = c(2, 2))

Calculate the relative frequency of the entire table.

prop.table(x)

Output:

     [,1] [,2]
[1,]  0.1  0.2
[2,]  0.3  0.4

Calculate the relative frequency by row.

prop.table(x, 1)

The output results:

     [,1] [,2]
[1,] 0.33 0.67
[2,] 0.43 0.57

Calculate the relative frequency by column:

prop.table(x, 2)

Output results:

     [,1] [,2]
[1,] 0.25  0.4
[2,] 0.75  0.6
bannerAds