【问题标题】:Is there a way in R to count the number of occurrences of a event between two different events?R中有没有办法计算两个不同事件之间的事件发生次数?
【发布时间】:2020-07-30 16:32:30
【问题描述】:

我正在分析轮作林业的管理,其中森林被种植,然后随着它的生长,通过采伐一些树木使其间伐几次,最后,所有树木都被砍伐。

以下是我的数据的示例:

year <- rep(seq(1,10, 1),3)
stand <- c(rep(1,10),rep(2,10),rep(3,10))
treatment <- c("planting", "none", "thinning", "none", "thinning", "none", "none", "felling", "planting", "none",
               "none", "planting", "thinning", "thinning", "thinning","none", "felling", "planting", "thinning", "none",
               "planting", "none", "thinning","none", "felling", "planting", "thinning","none", "thinning", "felling")
data <- data.frame(year,stand,treatment)

三个看台的旋转方式非常不同。

  • 第一年栽植1号台,第8年间伐2次,第9年再次栽植。1个完整轮作,每轮伐2次
  • 第 2 年栽植第 2 台,第 7 年间伐 3 次,然后砍伐。此后,种植新林并间伐一次,但轮作未完成。所以有一个旋转,每旋转有 3 次细化。
  • 支架 3 有两个旋转,其中一个在旋转 1 中变薄,在旋转 2 中两个。结果应该显示平均每个旋转有 1.5 个变薄。

我有数以千计的展位,有各种轮换时间表,所以我无法手动计算。如何编写脚本来计算每次完整轮作的间伐次数(种植和砍伐之间的年数)?

最后,我想要一张表格,上面有支架编号和每完整旋转的间伐次数。应丢弃所有不完整的旋转。

【问题讨论】:

  • 请包括 a) 您期望示例数据的结果是什么样的。 b) 通过提供有关您已经尝试实现目标的信息来激励帮助者。

标签: r dplyr time-series


【解决方案1】:

对于每个stand,我们可以保留第一个'planting' 和最后一个'felling' 之间的所有内容,因为我们只想考虑完全轮换。然后我们计算'thinning' 的数量并将其除以'planting' 的数量,这发生在stand 中,以获得每次旋转的细化。

library(dplyr)

data %>%
  group_by(stand) %>%
  filter(between(row_number(), min(which(treatment == 'planting')), 
                               max(which(treatment == 'felling')))) %>%
  summarise(thin_per_rotation = sum(treatment == 'thinning')/
                                sum(treatment == 'planting'))


#  stand thin_per_rotation
#  <dbl>             <dbl>
#1     1               2  
#2     2               3  
#3     3               1.5

【讨论】:

  • 那么第一次种植前的所有行也应该被删除。数据 %>% group_by(stand) %>% slice(min(which(treatment == 'felling')):length()) %>% slice(1:max(which(treatment == 'felling'))) %>% summarise(thin_per_rotation = sum(treatment == 'thinning')/ sum(treatment == 'planting'))
  • @triroba 你能在第一个'planting'之前有'thinning'吗?不过我已经更新了答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-22
  • 1970-01-01
相关资源
最近更新 更多