我正在使用一个非常大的tibble工作,并希望计算这些表随时间的增长百分比(首次进入最后一个条目,而不是最大值到最小值(。我最终还希望存储任何具有0个更改为自己列表/tibble的表格,但将它们从原始输出表中删除。
数据集的示例如下:
date tbl_name row_cnt
2/12/2019 first 247
6/5/2019 first 247
4/24/2019 second 3617138
6/5/2019 second 3680095
3/1/2019 third 62700321
6/5/2019 third 63509189
4/24/2019 fourth 2
6/5/2019 fourth 2
... ... ...
,表格的预期输出将是两个表格的表:
tbl_name pct_change
second 1.74
third 1.29
... ...
tbl_name
first
fourth
...
到目前为止,我已经能够安排观察值,对它们进行分组,并过滤每个组的第一个也是最后一个实例:
test_df <- df %>%
arrange(l.fully_qualf_tbl_nm) %>%
group_by(l.fully_qualf_tbl_nm) %>%
filter(row_number()==1 | row_number()==n()) %>%
mutate(pct_change = ((l.row_cnt/lag(l.row_cnt) - 1) * 100)) %>%
select(l.run_dt, l.fully_qualf_tbl_nm, pct_change) %>%
drop_na(pct_change)
但是我的计算
mutate(pct_change = ((l.row_cnt/lag(l.row_cnt) - 1) * 100)) %>%
没有生成正确的结果。我从另一个帖子中提取了我的PCT变化计算,该帖子讨论了%变化,但我的手指定数量不同。
例如,我得到了"第二= 3.61",但是手动计算(以及Excel(的收入为1.74。我还获得了"第三= 0.831",而不是单手1.29。我的猜测是,我不正确地指定我只想在每个组上完成计算(每对两行(。我想知道我是否应该分别计算滞后,还是仅仅是错误地实现了lag?
?接下来,我认为新表将以某种方式创建
if return value of filter(row_number()==1 | row_number()==n()) %>% == 0, append to list/table
但老实说,我不知道该怎么做。我想知道我是否应该单独执行一个函数并将其分配给新变量。
df <- read.table(
header = T,
stringsAsFactors = F,
text = " date tbl_name row_cnt
2/12/2019 first 247
6/5/2019 first 247
4/24/2019 second 3617138
6/5/2019 second 3680095
3/1/2019 third 62700321
6/5/2019 third 63509189
4/24/2019 fourth 2
6/5/2019 fourth 2")
# Wrapping in parentheses assigns the output to test_df and also prints it
(test_df <- df %>%
group_by(tbl_name) %>%
mutate(pct_change = ((row_cnt/lag(row_cnt) - 1) * 100)) %>%
ungroup() %>%
filter(!is.na(pct_change)) %>% # Filter after pct_change calc, since we want to
# include change from 1:2 and from n-1:n
select(tbl_name, row_cnt, pct_change))
# A tibble: 4 x 3
tbl_name row_cnt pct_change
<chr> <int> <dbl>
1 first 247 0
2 second 3680095 1.74
3 third 63509189 1.29
4 fourth 2 0
要分成两个表,似乎可以做:
first_tbl <- test_df %>% filter(pct_change != 0) # or "pct_change > 0" for pos growth
second_tbl <- test_df %>% filter(pct_change == 0)