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

R语言如何从向量取值为符合匹配条件的dataframe添加新行

方案1:tidyverse 简洁实现

需要加载dplyr和tidyr包,核心逻辑是先把匹配行的new_col存为向量列表,再拆分成多行:

library(dplyr)
library(tidyr)

result <- df %>%
  rowwise() %>%
  mutate(new_col = ifelse(w2 == "eat", list(vec), list("no correspondance"))) %>%
  unnest_longer(new_col)

方案2:基础R实现(无需加载额外包)

思路是拆分数据集分别处理后再合并:

# 拆分匹配和不匹配的行
match_rows <- df[df$w2 == "eat", ]
unmatch_rows <- df[df$w2 != "eat", ]

# 处理匹配行:重复length(vec)次,填充vec值
match_expanded <- match_rows[rep(seq(nrow(match_rows)), each = length(vec)), ]
match_expanded$new_col <- vec

# 处理不匹配行:直接填充默认值
unmatch_rows$new_col <- "no correspondance"

# 合并两个子集得到结果
result <- rbind(match_expanded, unmatch_rows)
# 若需保持原数据的行顺序可增加下行
result <- result[order(rownames(result)), ]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 10:54:06