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

如何在tibble中按行提取含x的值并新增列?

提取tibble每行含"x"的值生成新列

原始数据

现有如下tibble数据框:

df <- tibble(a = c(1,2,3,4,5,6,7,8,9,10),
             b = c("", "", "1", "", "1", "3", "2", "", "5", ""),
             c = c("", "", "", "", "x1", "x3", "x2", "", "x5", ""),
             d = c("", "", "1", "", "1", "3", "2", "", "5", ""),
             e = c("x1", "x4", "", "x5", "", "", "", "x2", "", "x2"))

需求

生成包含新列f的tibble,规则如下:

  • f列每行取值为该行中包含"x"的单元格值
  • 若该行无含"x"的值,则填充为空字符串
  • 无需指定具体列,适配任意数量的列

期望结果:

# A tibble: 10 × 6
       a b     c     d     e     f    
   <dbl> <chr> <chr> <chr> <chr> <chr>
 1     1 ""    ""    ""    "x1"  "x1" 
 2     2 ""    ""    ""    "x4"  "x4" 
 3     3 "1"   ""    "1"   ""    ""   
 4     4 ""    ""    ""    "x5"  "x5" 
 5     5 "1"   "x1"  "1"   ""    "x1" 
 6     6 "3"   "x3"  "3"   ""    "x3" 
 7     7 "2"   "x2"  "2"   ""    "x2" 
 8     8 ""    ""    ""    "x2"  "x2" 
 9     9 "5"   "x5"  "5"   ""    "x5" 
10    10 ""    ""    ""    "x2"  "x2" 

解决方案

方法1:dplyr + purrr逐行处理

通过pmap_chr逐行遍历,筛选含"x"的元素,取第一个(适配每行最多一个目标值的场景),无匹配则返回空字符串:

library(dplyr)
library(purrr)
library(stringr)

df %>%
  mutate(f = pmap_chr(., ~ {
    vals <- c(...)
    target <- str_subset(vals, "x")
    ifelse(length(target) > 0, target[1], "")
  }))

方法2:rowwise + c_across(dplyr 1.0.0+)

用rowwise按行分组,c_across获取所有列的值后筛选目标元素:

library(dplyr)
library(stringr)

df %>%
  rowwise() %>%
  mutate(f = {
    target <- str_subset(c_across(everything()), "x")
    ifelse(length(target) > 0, target[1], "")
  }) %>%
  ungroup()

方法3:向量化处理(高效适配大数据集)

避免逐行循环,通过矩阵操作实现批量处理:

library(dplyr)
library(stringr)

# 生成标记含"x"位置的逻辑矩阵
x_flag_matrix <- str_detect(df, "x")
# 提取每行第一个目标值,无则为空
df$f <- apply(x_flag_matrix, 1, function(row) {
  if (any(row)) df[row, which(row)][[1]] else ""
})

以上三种方法均无需指定具体列名,可适配任意数量的列。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 12:16:02