Learn R Programming

sjstats (version 0.7.1)

prop: Proportion of values in a vector

Description

This function calculates the proportion of a value or category in a variable.

Usage

prop(data, ..., weight.by = NULL, na.rm = FALSE, digits = 4)

Arguments

data
A data frame.
...
One or more value pairs of comparisons (logical predicates). Put variable names the left-hand-side and values to match on the right hand side. Expressions may be quoted or unquoted. See 'Examples'.
weight.by
Vector of weights that will be applied to weight all observations. Must be a vector of same length as the input vector. Default is NULL, so no weights are used.
na.rm
Logical, whether to remove NA values from the vector when the proportion is calculated. na.rm = FALSE gives you the raw percentage of a value in a vector, na.rm = TRUE the valid percentage.
digits
Amount of digits for returned values.

Value

For one condition, a numeric value with the proportion of the values inside a vector. For more than one condition, a tibble with one column of conditions and one column with proportions.

Examples

Run this code
data(efc)

# proportion of value 1 in e42dep
prop(efc, e42dep == 1)

# expression may also be completely quotes
prop(efc, "e42dep == 1")

# proportion of value 1 in e42dep, and all values greater
# than 2 in e42dep, excluding missing values. will return a tibble
prop(efc, e42dep == 1, e42dep > 2, na.rm = TRUE)


# for factors or character vectors, use quoted or unquoted values
library(sjmisc)
# convert numeric to factor, using labels as factor levels
efc$e16sex <- to_label(efc$e16sex)

# get proportion of female older persons
prop(efc, e16sex == female)

# get proportion of male older persons
prop(efc, e16sex == "male")

# also works with pipe-chains
library(dplyr)
efc %>% prop(e17age > 70)
efc %>% summarise(age70 = prop(., e17age > 70))

# and with group_by
efc %>%
  group_by(e16sex) %>%
  summarise(hi.dependency = prop(., e42dep > 2))

Run the code above in your browser using DataLab