繁体   English   中英

两列之间的算术运算,在dplyr中滞后一行

[英]Arithmetic between two columns, lagged by one row in dplyr

不确定最好的措辞方式,但我想将两列相互多行/除行,而滞后一行(在我的数据集中,这意味着varx / vary-1行)。

最终结果应该是带有一个NA值的附加列(对于第一年不存在)

我在为它编制索引时遇到麻烦,但我认为它会沿这些方向发展...

例如

df <- data_frame(year = c(2010:2020), var_x = c(20:30), var_y = c(2:12))


#not correct
diff <- df[,2, 2:ncol(df)-1] * df[,3, 1:ncol(df)]
dplyr would look something like...

df %>% 
  mutate(forecast = (var_x * ncol(var_y)-1))

incorrect result:
# A tibble: 11 x 4
    year var_x var_y forecast
   <int> <int> <int>    <int>
 1  2010    20     2       40
 2  2011    21     3       63
 3  2012    22     4       88
 4  2013    23     5      115
 5  2014    24     6      144
 6  2015    25     7      175
 7  2016    26     8      208
 8  2017    27     9      243
 9  2018    28    10      280
10  2019    29    11      319
11  2020    30    12      360


Error in mutate_impl(.data, dots) : 
  Column `forecast` must be length 11 (the number of rows) or one, not 0

谢谢,感谢您的指导。

来自上面的推荐评论:

df %>% 
mutate(forecast = var_y * lag(var_x))

# A tibble: 11 x 4
    year var_x var_y forecast
   <int> <int> <int>    <int>
 1  2010    20     2       NA
 2  2011    21     3       60
 3  2012    22     4       84
 4  2013    23     5      110
 5  2014    24     6      138
 6  2015    25     7      168
 7  2016    26     8      200
 8  2017    27     9      234
 9  2018    28    10      270
10  2019    29    11      308
11  2020    30    12      348

暂无
暂无

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

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