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

如何在R中使用dplyr根据列条件选择特定前缀列并整理格式?

使用dplyr实现条件选择列并重命名的操作

首先构造一个符合需求的示例数据集,方便验证代码:

library(dplyr)
library(tidyr)

# 示例tibble
df <- tibble(
  date = as.Date(c("2023-01-01", "2023-01-02", "2023-01-03")),
  var = c("x", "y", "z"),
  cat_low = c(1, 2, 3),
  cat_high = c(4, 5, 6),
  dog_low = c(7, 8, 9),
  dog_high = c(10, 11, 12),
  Love = c("love", "other", "love"),
  Friend = c("other", "friend", "other")
)

接下来用dplyr结合tidyr实现你的需求:

result <- df %>%
  rowwise() %>%
  mutate(
    # 根据条件选择对应前缀的列,并重命名为a、b
    selected_cols = case_when(
      Love == "love" ~ list(pick(starts_with("cat")) %>% rename(a = 1, b = 2)),
      Friend == "friend" ~ list(pick(starts_with("dog")) %>% rename(a = 1, b = 2)),
      # 不满足条件的行填充NA
      TRUE ~ list(tibble(a = NA_real_, b = NA_real_))
    )
  ) %>%
  ungroup() %>%
  # 展开嵌套的列
  unnest(selected_cols) %>%
  # 保留需要的列
  select(date, var, a, b)

代码说明:

  • rowwise():开启按行处理模式,适配每行不同的判断条件。
  • case_when():根据Love或Friend的取值分支处理:
    • 当Love == "love"时,用pick(starts_with("cat"))选中所有以cat开头的列,再通过rename(a=1, b=2)把选中的第一列重命名为a,第二列重命名为b,用list()包装成嵌套tibble。
    • 当Friend == "friend"时,同理选中以dog开头的列并重命名。
    • 不满足条件的行生成包含NA的a、b列。
  • ungroup():取消行分组,恢复常规数据框操作。
  • unnest(selected_cols):把嵌套的tibble展开,将a、b列合并到主数据中。
  • select():最终保留date、var、a、b目标列。

运行后得到的结果如下:

# A tibble: 3 × 4
  date       var       a     b
  <date>     <chr> <dbl> <dbl>
1 2023-01-01 x         1     4
2 2023-01-02 y         8    11
3 2023-01-03 z         3     6

内容的提问来源于stack exchange,提问作者Homer Jay Simpson

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 05:55:15