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

如何在dplyr的mutate(across)中结合列名与类型双重条件修改数据?

解决方法

你的问题出在列名筛选和类型筛选的用法混淆:ends_with()是针对列名的tidyselect选择器,不能放在where()的函数内部(where()的函数是作用于列的数值向量)。正确的做法是将列名筛选和类型筛选直接组合作为across()的第一个参数:

正确代码示例

df %>% 
  mutate(
    across(
      ends_with("1") & where(is.numeric),
      ~ .x * 2
    )
  )

执行后结果:

a1 b1 c
1  2  1 1
2  4  2 2
3  6  3 3
4  8  4 4
5 10  5 5

另一种等价写法

也可以用正则匹配列名结尾的"1",效果完全一致:

df %>% 
  mutate(
    across(
      matches("1$") & where(is.numeric),
      ~ .x * 2
    )
  )

错误原因说明

你之前的代码中,where(~ ends_with('1') && is.numeric(.))逻辑错误:ends_with()无法识别列的数值向量作为输入,它只能用于匹配列名,所以这个条件实际上只生效了is.numeric(.),导致c列也被选中修改。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 13:52:08