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

如何在R语言中检查本周与上周的数据是否匹配

在R中为DataFrame新增匹配上周字符串的列

核心思路

通过对比当前行的Data值与上一行的Data值生成Match列:若两者相同则标记为1,否则为0;第一行因无前置数据,直接设为0。

方法一:Base R(无需额外包)

直接通过索引定位上一行数据进行对比,将结果转换为整数后,替换第一行的缺失值为0:

# 构造示例数据
df <- data.frame(
  Week = 1:10,
  Data = c("Red", "Blue", "Blue", "Yellow", "Green", "Blue", "Blue", "Blue", "Green", "Yellow")
)

# 新增Match列
df$Match <- as.integer(df$Data == c(NA, df$Data[-nrow(df)]))
df$Match[is.na(df$Match)] <- 0

方法二:使用dplyr(tidyverse生态)

借助dplyr的lag()函数获取上一行数据,配合mutate()生成新列,并用replace_na()处理第一行的缺失值:

library(dplyr)

# 构造示例数据(同上)
df <- data.frame(
  Week = 1:10,
  Data = c("Red", "Blue", "Blue", "Yellow", "Green", "Blue", "Blue", "Blue", "Green", "Yellow")
)

# 新增Match列
df <- df %>%
  mutate(Match = as.integer(Data == lag(Data))) %>%
  replace_na(list(Match = 0))

重要提示

确保你的DataFrame已经按Week列升序排列,否则对比的将不是"上周"的数据,导致结果错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 11:02:07