These functions weight the variable x by
a specific vector of weights.
weight(x, weights, digits = 0)
weight2(x, weights)(Unweighted) variable.
Vector with same length as x, which
contains weight factors. Each value of x has a
specific assigned weight in weights.
Numeric value indicating the number of decimal places to be
used for rounding the weighted values. By default, this value is
0, i.e. the returned values are integer values.
The weighted x.
weight2() sums up all weights values of the associated
categories of x, whereas weight() uses a
xtabs formula to weight cases. Thus, weight()
may return a vector of different length than x.
The values of the returned vector are in sorted order, whereas the values'
order of the original x may be spread randomly. Hence, x can't be
used, for instance, for further cross tabulation. In case you want to have
weighted contingency tables or (grouped) box plots etc., use the weightBy
argument of most functions.
v <- sample(1:4, 20, TRUE)
table(v)
#> v
#> 1 2 3 4
#> 3 6 5 6
w <- abs(rnorm(20))
table(weight(v, w))
#>
#> 1 2 3 4
#> 2 5 5 3
table(weight2(v, w))
#>
#> 1 2 3 4
#> 2 5 5 3
set.seed(1)
x <- sample(letters[1:5], size = 20, replace = TRUE)
w <- runif(n = 20)
table(x)
#> x
#> a b c d e
#> 6 4 3 1 6
table(weight(x, w))
#>
#> a b c e
#> 3 3 2 3