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

R如何用dplyr管道符单行实现按指定列提取对应列的数值

实现方案

完全可以用单行dplyr管道代码实现需求,以下提供两种常用方案:

  • 方案1:rowwise实现,逻辑简单易读,适合中小体量数据集
library(tidyverse)
# 单行管道实现
example %>% rowwise() %>% mutate(result = get(choose))
  • 方案2:向量化矩阵索引实现,无行迭代开销,性能更高,适合大数据集
example %>% mutate(result = cur_data()[cbind(1:n(), choose)])

两种方案输出结果都和现有实现完全一致:

A  B  C choose result
1  9 12  4      A      9
2  7  8 13      C     13
3  5  1  2      A      5
4 15  3 11      C     11
5 14  6 10      B      6

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 21:54:10