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

如何在R语言中按条件统计状态出现次数

状态序列统计问题

输入数据

str_eg <- c("-", "-", "-", "+", "-", "+", "-", "-", "-", "+")

统计需求

  • 统计状态-出现在-之后的次数,预期结果:minus_after_minus <- 4
  • 统计状态+出现在-之后的次数,预期结果:plus_after_minus <- 3

实现代码与验证

在R中可通过提取相邻状态对完成统计:

# 拆分出相邻的前状态和后状态序列
prev <- head(str_eg, -1)
next <- tail(str_eg, -1)

# 统计"-"后接"-"的次数
minus_after_minus <- sum(prev == "-" & next == "-")
# 结果:4

# 统计"-"后接"+"的次数
plus_after_minus <- sum(prev == "-" & next == "+")
# 结果:3

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 03:00:56