各位
假设我有一个如下所示的数据集:
id value year total_value total_frequency
1 10 2019 44 4
1 15 2019 44 4
1 12 2020 44 4
1 7 2020 44 4
2 10 2019 28 2
2 18 2020 28 2
3 27 2019 27 1
我打算实现这样的形式:
id value year total_value total_frequency 2020_value 2020_frequency
1 10 2019 44 4 19 2
1 15 2019 44 4 19 2
1 12 2020 44 4 19 2
1 7 2020 44 4 19 2
2 10 2019 28 2 18 1
2 18 2020 28 2 18 1
3 27 2019 27 1 0 0
重复对于以后的步骤是必要的。
我可以使用 sumifs() 和 countifs() 通过 Excel 轻松实现此表单,但无法在 R 中获得相同的结果。
我认为我可以使用 dplyr 包来执行此操作,但不知 Prop 体如何操作,因此需要一些建议。
最佳答案
按 id
进行分组,并对 2020 年年份
的值
进行求和
,并计算行数也是如此。
library(dplyr)
df %>%
group_by(id) %>%
mutate(value_2020 = sum(value[year %in% 2020]),
frequency_2020 = sum(year %in% 2020)) %>%
ungroup
# id value year total_value total_frequency value_2020 frequency_2020
# <int> <int> <int> <int> <int> <int> <int>
#1 1 10 2019 44 4 19 2
#2 1 15 2019 44 4 19 2
#3 1 12 2020 44 4 19 2
#4 1 7 2020 44 4 19 2
#5 2 10 2019 28 2 18 1
#6 2 18 2020 28 2 18 1
#7 3 27 2019 27 1 0 0
关于r - R 中的 sumif 和 countif 等效项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66741290/