繁体   English   中英

访问前一行以在 R 中的当前行中进行计算

[英]Accessing previous rows to make a calculation in a current row in R

我有需要在行子组内进行计算的数据。 具体来说,我正在计算不同田间处理之间作物的氮 (N) 回收效率。 这需要找出施用给定量 N (Nrate) 的 plot 和施用 0 N 的对照 plot 之间的作物 N 吸收差异 (totN),然后除以 Nrate。

这是数据仅一年的样子:

year drain Nrate  totN 
2016 C         0   190 
2016 C       100   220 
2016 C       200   230 
2016 N         0   130 
2016 N       100   200 
2016 N       200   220 

由于在 R 中的行之间执行计算,我已经走到了这一步,但我不确定如何在每行所在的子组中引用控制行(Nrate = 0)。

这就是我所在的位置:

library(tidyverse)

df <- data.frame(year=c(2016,2016,2016,2016,2016,2016),
                 drain=c("C","C","C","N","N","N"),
                 Nrate=c(0,100,200,0,100,200),
                 totN=c(190,220,230,130,200,220))

df %>%
  group_by(year,drain) %>%
  mutate(id = row_number()) %>%
  mutate(RE = ifelse(id != 1,
                     (totN - <the totN where Nrate=0 for same year and drain>) / Nrate,
                     NA))

这是我期望得到的:

year drain Nrate  totN  RE
2016 C         0   190  NA
2016 C       100   220  0.3  (220-190)/100
2016 C       200   230  0.2  (230-190)/200
2016 N         0   130  NA
2016 N       100   200  0.7  (200-130)/100
2016 N       200   220  0.45 (220-130)/200

我们可以通过索引来对“totN”进行子集化,或者如果它已经排序,则使用first(totN)

library(dplyr)
df %>%
   group_by(year, drain) %>% 
   mutate(RE = na_if((totN - totN[Nrate == 0])/Nrate, "NaN")) %>%
   ungroup

-输出

# A tibble: 6 x 5
#   year drain Nrate  totN    RE
#  <dbl> <chr> <dbl> <dbl> <dbl>
#1  2016 C         0   190 NA   
#2  2016 C       100   220  0.3 
#3  2016 C       200   230  0.2 
#4  2016 N         0   130 NA   
#5  2016 N       100   200  0.7 
#6  2016 N       200   220  0.45

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM