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

R语言dataframe中如何为列表列元素拼接同行列字符串首尾字符

实现思路

核心逻辑是逐行匹配id列与furniture列的取值:先将数值型id转换为字符串避免截取错误,对每一行分别提取id的前3位作为前缀、后3位作为后缀,再遍历该行furniture列表内的所有元素,按「前缀+列表元素+后缀」的规则拼接,最终生成新的output列即可。以下提供两种可直接运行的实现方案:

方案1:tidyverse 写法(简洁易读,推荐日常使用)

依赖dplyr做数据框操作、purrr做行级映射、stringr做稳定的字符串截取,代码逻辑清晰不易出错:

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

# 构造示例数据
tester <- data.frame(id = c(123456789, 987654321))
tester$furniture <-  list(c("chair", "couch"), c("bed", "bench"))

# 生成output列
tester <- tester %>%
  mutate(
    id_str = as.character(id),
    output = pmap(
      list(id_str, furniture),
      function(cur_id, cur_furn) {
        pre <- str_sub(cur_id, 1, 3)
        suf <- str_sub(cur_id, -3, -1)
        paste0(pre, cur_furn, suf)
      }
    )
  ) %>%
  select(-id_str)

运行后直接查看tester$output即可得到和预期完全一致的结果。

方案2:Base R 写法(无需安装第三方包)

如果不想加载额外扩展包,用R原生函数即可实现相同效果:

# 构造示例数据
tester <- data.frame(id = c(123456789, 987654321))
tester$furniture <-  list(c("chair", "couch"), c("bed", "bench"))

# 生成output列
tester$id_str <- as.character(tester$id)
tester$output <- apply(
  tester,
  1,
  function(row) {
    cur_id <- row[["id_str"]]
    id_len <- nchar(cur_id)
    pre <- substr(cur_id, 1, 3)
    suf <- substr(cur_id, id_len - 2, id_len)
    paste0(pre, unlist(row[["furniture"]]), suf)
  }
)
tester$id_str <- NULL
注意事项
  • 必须先将id列转换为字符类型再做截取,若直接操作数值型字段,容易因科学计数法转换、长度计算偏差导致结果错误
  • 两种方案均兼容空值场景:若某行furniture列存储空列表,代码不会中断运行,会对应返回空结果
  • 若存在id长度不足3位的情况,代码会自动提取现有长度的字符做拼接,不会抛出异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 15:57:52