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

在dplyr中是否存在可计算数值倒数的函数?

在dplyr中获取向量元素倒数的实现方式

首先明确:dplyr本身没有内置名为reciprocalfunction的函数,但可以通过两种简单方式实现你想要的效果:

方式一:直接用管道结合除法操作

利用管道符%>%的特性,.代表传递过来的前一个对象(也就是这里的1:5向量),直接计算倒数即可:

Reciprocal <- 1:5 %>% 
  {1 / .}

Reciprocal

执行后会得到预期结果:

[1] 1.0000000 0.5000000 0.3333333 0.2500000 0.2000000

方式二:自定义你想要的reciprocalfunction函数

如果一定要用类似reciprocalfunction()的调用形式,完全可以自己定义这个函数,之后就能按你的代码格式使用:

# 自定义倒数函数
reciprocalfunction <- function(x) {
  1 / x
}

# 使用管道调用
Reciprocal <- 1:5 %>% 
  reciprocalfunction()

Reciprocal

这段代码同样会输出你需要的倒数结果。

补充:处理数据框列的场景

如果是处理数据框中的列,结合dplyr的mutate也能轻松实现,比如:

library(dplyr)

df <- tibble(num = 1:5) %>% 
  mutate(reciprocal = 1 / num)

df

输出结果会是包含原列和倒数列的数据框:

# A tibble: 5 × 2
    num reciprocal
  <int>      <dbl>
1     1      1    
2     2      0.5  
3     3      0.333
4     4      0.25 
5     5      0.2  

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 13:24:28