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

使用dplyr将数据框text=@行的word列值复制到上方text=d行

解决方案:将text=@行的word内容回填到上方text=d行

针对你需要把text列等于@的行的word信息复制到其上方text列等于d的行的需求,这里提供一个基于dplyr包的简洁实现方案:

步骤1:构造示例数据

首先我们先还原你的原始数据框(你可以直接替换成自己的真实数据):

library(dplyr)

df <- tibble(
  word = c(NA, "tour de rôle", NA, NA, "colonie de vacances", NA, NA, "pantalon de coton", NA, NA),
  dur = c(50.0000, 30.0000, 90.0000, 60.0000, 70.0000, 40.0000, 110.0000, 60.0000, 80.0000, 90.0000),
  schwa = c(FALSE, TRUE, NA, FALSE, TRUE, FALSE, FALSE, TRUE, FALSE, FALSE),
  text = c("d", "@", NA, "d", "@", "FALSE", "d", "@", "FALSE", "FALSE")
)

步骤2:数据处理

核心思路是利用lead()函数获取下一行的word值,然后针对text=d的行进行替换:

df_processed <- df %>%
  # 新增临时列,存储下一行的word内容
  mutate(next_word = lead(word)) %>%
  # 当当前行text为"d"时,用下一行的word替换当前行的word
  mutate(word = ifelse(text == "d", next_word, word)) %>%
  # 移除临时列
  select(-next_word)

验证结果

处理后的df_processed就会和你期望的结果一致:

worddurschwatext
tour de rôle50.000FALSEd
tour de rôle30.000TRUE@
NA90.000NANA
colonie de vacances60.000FALSEd
colonie de vacances70.000TRUE@
NA40.000FALSEFALSE
pantalon de coton110.000FALSEd
pantalon de coton60.000TRUE@
NA80.000FALSEFALSE
NA90.000FALSEFALSE

这个方案逻辑清晰,只需要简单的两步mutate就能完成需求,完全适配你给出的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:54:36