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

在R中实现连续行Column C值校验及Column A/B大小对比

R语言实现连续行分组对比需求

首先,将你的数据集转换成R可处理的数据框:

df <- data.frame(
  Column_A = c(3, 5, 7, 6, 9),
  Column_B = c(6, 7, 11, 12, 13),
  Column_C = c("EuropeGreece", "EuropeGreece", "EuropeBelgium", "EuropeBelgium", "EuropeCrotia")
)

方法一:使用dplyr(tidyverse)

借助dplyr的lag()函数获取上一行数据,再通过case_when()按规则生成结果:

library(dplyr)

df <- df %>%
  mutate(
    # 判断当前行与上一行的Column C是否相同
    same_group = Column_C == lag(Column_C),
    # 判断当前行的A、B是否大于上一行
    A_increase = Column_A > lag(Column_A),
    B_increase = Column_B > lag(Column_B),
    # 按规则生成结果
    result = case_when(
      # 第一行无前置行,返回"N/A"
      is.na(same_group) ~ "N/A",
      # 分组不同时返回"N/A"
      !same_group ~ "N/A",
      # 分组相同时返回A、B是否都递增的结果(转字符避免与FALSE混淆)
      TRUE ~ as.character(A_increase & B_increase)
    )
  )

方法二:基础R实现

无需额外包,用向量操作完成需求:

# 生成分组相同标记(第一行为NA)
same_group <- c(NA, df$Column_C[-1] == df$Column_C[-nrow(df)])
# 生成A、B列递增标记(第一行为NA)
A_inc <- c(NA, df$Column_A[-1] > df$Column_A[-nrow(df)])
B_inc <- c(NA, df$Column_B[-1] > df$Column_B[-nrow(df)])

# 按规则生成结果列
df$result <- ifelse(
  is.na(same_group) | !same_group, 
  "N/A", 
  as.character(A_inc & B_inc)
)

最终结果

运行后的数据框如下:

Column_AColumn_BColumn_Cresult
36EuropeGreeceN/A
57EuropeGreeceTRUE
711EuropeBelgiumN/A
612EuropeBelgiumFALSE
913EuropeCrotiaN/A

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 08:42:17