You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写可在dplyr::mutate()中运行的自定义行求和函数

Optimize Row Sum Function for dplyr::mutate() (No Explicit . Required)

If you're tired of having to pass . to your custom row sum function every time you use it in dplyr::mutate()—and want to ditch the slow rowwise() workflow in favor of base R's lightning-fast rowSums()—here's exactly how to fix this:

The Problem: Why You Had to Pass .

Let’s start with the common scenario that led you here. Suppose you first wrote a function like this, using rowSums() for performance:

# Original function (requires explicit `.` in mutate)
row_sum_old <- function(df, na.rm = TRUE) {
  rowSums(df, na.rm = na.rm)
}

When you tried to use this in mutate() without passing ., you got an error:

Error in rowSums(df, na.rm = na.rm) : argument "df" is missing, with no default

To make it work, you had to explicitly pass the current data frame with .:

# Works, but is repetitive
df %>% mutate(total = row_sum_old(., value1, value2, value3))

That’s clunky. Let’s fix it so you don’t need to pass . ever again.

Solution 1: Sum Specific Columns (Unquoted Names)

This function lets you pass unquoted column names directly in mutate(), no . required. It uses dplyr::cur_data() to automatically access the current data frame in the mutate context:

library(dplyr)

row_sum <- function(..., na.rm = TRUE) {
  # Grab the current data frame and select the specified columns
  selected_cols <- cur_data() %>% select(...)
  # Apply rowSums to the selected columns
  rowSums(selected_cols, na.rm = na.rm)
}

Example Usage:

# Sample data frame
df <- tibble(
  id = 1:3,
  value1 = c(10, 20, NA),
  value2 = c(5, NA, 15),
  value3 = c(7, 8, 9)
)

# Sum specific columns without passing `.`
df %>% mutate(total = row_sum(value1, value2, value3))

Output:

# A tibble: 3 × 5
     id value1 value2 value3 total
  <int>  <dbl>  <dbl>  <dbl> <dbl>
1     1     10      5      7    22
2     2     20     NA      8    28
3     3     NA     15      9    24

Solution 2: Sum All Numeric Columns (No Arguments Needed)

If you want to sum every numeric column in your data frame without specifying each one, use this variant:

row_sum_all <- function(na.rm = TRUE) {
  # Select all numeric columns from the current data frame
  numeric_cols <- cur_data() %>% select(where(is.numeric))
  rowSums(numeric_cols, na.rm = na.rm)
}

Example Usage:

df %>% mutate(total_all = row_sum_all())

Why This Works

dplyr::cur_data() is the magic here—it returns the subset of the data frame that’s currently being processed in mutate() (including any prior mutations). This means your function automatically has access to the data frame without you needing to pass . explicitly.

And since we’re using base R’s rowSums(), this is drastically faster than using rowwise() %>% mutate(total = sum(...))—especially on large datasets with thousands or millions of rows.


内容的提问来源于stack exchange,提问作者jzadra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:31:04