Given one or more vectors, psum()
and pmean()
return row-wise sums or means. They are analogous to base::pmin()
and pmax()
. Like pmin()
/ pmax()
, these functions:
accept multiple vectors via
...
(as opposed torowSums()
androwMeans()
, which accept a single array). This allows them to be used in data-masking contexts (e.g., insidedplyr::mutate()
).return
NA
when all values areNA
andna.rm = TRUE
. (as opposed torowSums()
, which returns0
in this situation).
Details
Both psum()
and psum_across()
can be used in data-masking contexts, but
have different capabilities and limitations. See the "Details" section of
?psum_across
.
Note that, unlike pmin()
, pmax()
, rowSums()
, and rowMeans()
, these
functions do not currently support objects with more than one dimension
(e.g., matrices, arrays, or data frames).
See also
psum_across()
for variants that support tidyselect expressions. See the "Details" section for relative strengths ofpsum()
/pmean()
vs.psum_across()
/pmean_across()
.base::pmin()
for analogouspmin()
andpmax()
functionssum_if_any()
for non-parallel sums with similarNA
handling
Examples
psum(1:5, 6:10)
#> [1] 7 9 11 13 15
pmean(1:5, 6:10)
#> [1] 3.5 4.5 5.5 6.5 7.5
dat <- tibble::tribble(
~product, ~price1, ~price2, ~price3,
"Product 1", 20, 25, 22,
"Product 2", NA, 30, 29,
"Product 3", 15, NA, NA,
"Product 4", NA, NA, NA
)
# contrast w `rowSums()` / `rowMeans()`:
# no need for `pick()` and different `NA` behavior
dat %>%
dplyr::mutate(
rowSums = rowSums(pick(price1, price2, price3), na.rm = TRUE),
psum = psum(price1, price2, price3, na.rm = TRUE),
rowMeans = rowMeans(pick(price1, price2, price3), na.rm = TRUE),
pmean = pmean(price1, price2, price3, na.rm = TRUE)
)
#> # A tibble: 4 × 8
#> product price1 price2 price3 rowSums psum rowMeans pmean
#> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 Product 1 20 25 22 67 67 22.3 22.3
#> 2 Product 2 NA 30 29 59 59 29.5 29.5
#> 3 Product 3 15 NA NA 15 15 15 15
#> 4 Product 4 NA NA NA 0 NA NaN NA