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

如何用dplyr筛选含未知公共后缀的cnt_与pct_配对列?

动态匹配计数与百分比列并合并

问题说明

通过前期数据操作生成了计数列(格式为cnt_后缀)和百分比列(格式为pct_后缀),但列名的后缀是动态生成的,无法提前预知。需要自动匹配每组同后缀的cnt和pct列,将它们合并为计数 (百分比)格式的结果列。

示例数据

假设我们有如下生成的示例数据(后缀something和otherthing是动态生成的,实际场景中无法提前知晓):

library(tidyverse)

mtcars <- mtcars %>% 
    mutate(cnt_something = sample(0:100, nrow(mtcars)),
           cnt_otherthing = sample(0:100, nrow(mtcars)),
           pct_something = paste0( cnt_something, "%"),
           pct_otherthing = paste0( cnt_otherthing, "%"))

解决方案

核心是先提取所有cnt_开头列的后缀,再逐个匹配对应的pct_列并合并:

# 提取所有cnt列的后缀
suffixes <- mtcars %>%
  select(starts_with("cnt_")) %>%
  colnames() %>%
  str_remove("cnt_")

# 遍历后缀,合并每组cnt和pct列
result <- mtcars %>%
  # 只保留cnt和pct开头的列
  select(starts_with("cnt_"), starts_with("pct_")) %>%
  # 逐行处理
  pmap_dfr(function(...) {
    row_data <- tibble(...)
    # 为每个后缀生成合并后的结果列
    map_dfc(suffixes, ~{
      tibble(!!paste0("result_", .x) := paste0(row_data[[paste0("cnt_", .x)]], " (", row_data[[paste0("pct_", .x)]], ")"))
    })
  }) %>%
  # 合并原数据的行名(车型名称)
  bind_cols(rownames_to_column(mtcars, "car_model") %>% select(car_model), .) %>%
  column_to_rownames("car_model")

# 查看前几行结果
head(result)

输出结果

执行上述代码后,会得到如下格式的结果:

result_something result_otherthing
Mazda RX4                   49 (49%)          82 (82%)
Mazda RX4 Wag               20 (20%)          72 (72%)
Datsun 710                  37 (37%)          75 (75%)
Hornet 4 Drive              22 (22%)          85 (85%)
Hornet Sportabout           53 (53%)        100 (100%)
Valiant                     11 (11%)          45 (45%)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 01:10:28