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

如何合并position与substitution列生成指定格式的氨基酸替换列?

解决方案

需求说明

需要将tibble中逗号分隔的position列与同结构的substitution列配对处理:把每个substitution元素(如A/B)中的/替换为position列对应索引的数字,最终合并为新的combined列。

实现代码

library(tidyverse)

# 示例数据
df <- tibble(name = c("A", "B"),
             position = c("123, 45", "67, 891, 23"),
             substitution = c("A/B, C/D", "E/F, G/H, J/K"))

# 核心处理逻辑
df <- df %>%
  rowwise() %>%
  mutate(
    # 拆分两列为元素列表(按", "分隔)
    pos_elements = str_split(position, ",\\s+")[[1]],
    sub_elements = str_split(substitution, ",\\s+")[[1]],
    # 配对替换:将每个sub元素的"/"替换为对应位置的数字
    combined_elements = map2_chr(sub_elements, pos_elements, ~str_replace(.x, "/", .y)),
    # 重新合并为逗号分隔的字符串
    combined = str_c(combined_elements, collapse = ", ")
  ) %>%
  # 清理临时列
  select(-pos_elements, -sub_elements, -combined_elements)

# 查看结果
print(df)

代码解释

  • rowwise():确保每一行独立处理,避免跨行的向量运算错误
  • str_split(..., ",\\s+"):按逗号加任意空格拆分字符串,得到每个位置/替换对的独立元素
  • map2_chr():同步遍历两个元素列表,对每一对执行替换操作,返回字符向量
  • str_c(..., collapse = ", "):将处理后的单个元素重新合并为目标格式的字符串

运行结果

# A tibble: 2 × 4
  name  position     substitution     combined              
  <chr> <chr>        <chr>            <chr>                 
1 A     123, 45      A/B, C/D         A123B, C45D           
2 B     67, 891, 23  E/F, G/H, J/K    E67F, G891H, J23K

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 02:17:01