在R的dplyr中使用mutate+rowSums添加求和列的问题
问题:将指定列的行求和结果添加到原数据框
需求
对数据框newdf4中存在的指定列(adSize_300 x 600、adSize_160 x 600、adSize_120 x 600、adSize_125 x 600)进行行求和,将结果作为新列vertical_sizes添加到原数据框中。
初次尝试的代码及结果
尝试以下代码后,仅得到包含目标列和新列的子数据框,而非完整的原数据框:
newdf4 %>% select(any_of(contains(c("adSize_300 x 600","adSize_160 x 600","adSize_120 x 600","adSize_125 x 600")))) %>% mutate(vertical_sizes=rowSums(.))
输出结果:
adSize_300 x 600 adSize_160 x 600 vertical_sizes 1 1 0 1 2 0 0 0 3 0 0 0 4 0 0 0 5 0 1 1 6 0 0 0 7 1 0 1 8 0 0 0 9 0 0 0 10 0 0 0 11 0 0 0
第二次尝试的代码及错误
尝试直接在mutate中生成新列时,触发如下错误:
newdf4 %>% mutate(vertical_sizes = rowSums(select(any_of(contains(c("adSize_300 x 600","adSize_160 x 600","adSize_120 x 600","adSize_125 x 600"))))))
错误信息:
Error in `mutate_cols()`: ! Problem with `mutate()` column `vertical_sizes`. i `vertical_sizes = rowSums(...)`. x `any_of()` must be used within a *selecting* function. i See <https://tidyselect.r-lib.org/reference/faq-selection-context.html>. Caused by error: ! `any_of()` must be used within a *selecting* function. i See <https://tidyselect.r-lib.org/reference/faq-selection-context.html>. Run `rlang::last_error()` to see where the error occurred.
解决方案
以下三种方法均可实现需求:
方法1:使用across处理列选择
across是tidyverse中适配mutate上下文的列选择工具,可直接配合any_of使用:
newdf4 %>% mutate(vertical_sizes = rowSums(across(any_of(c("adSize_300 x 600", "adSize_160 x 600", "adSize_120 x 600", "adSize_125 x 600")))))
方法2:先提取存在的目标列名
先筛选出数据框中实际存在的目标列,再对这些列求和:
target_cols <- intersect(colnames(newdf4), c("adSize_300 x 600", "adSize_160 x 600", "adSize_120 x 600", "adSize_125 x 600")) newdf4 %>% mutate(vertical_sizes = rowSums(across(all_of(target_cols))))
方法3:用cur_data()提供选择上下文
通过cur_data()在mutate中获取完整数据框,让select拥有正确的执行上下文:
newdf4 %>% mutate(vertical_sizes = rowSums(select(cur_data(), any_of(c("adSize_300 x 600", "adSize_160 x 600", "adSize_120 x 600", "adSize_125 x 600")))))
内容的提问来源于stack exchange,提问作者Jess
相关产品推荐
相关产品推荐

