gpt4 book ai didi

r - 总结一年内的公司数量

转载 作者:行者123 更新时间:2023-12-01 07:34:05 24 4
gpt4 key购买 nike

假设我有一个如下的数据框:

dt=structure(list(id = c(1L, 1L, 1L, 1L, 2L, 3L, 3L, 3L, 4L, 4L, 
4L, 4L, 5L, 5L, 6L, 6L), year = c(2001L, 2002L, 2003L, 2004L,
2002L, 2002L, 2003L, 2004L, 2002L, 2003L, 2004L, 2005L, 2001L,
2002L, 2001L, 2002L)), .Names = c("firm", "year"), row.names = c(NA,
-16L), class = "data.frame")

dt
firm year
1 1 2001
2 1 2002
3 1 2003
4 1 2004
5 2 2002
6 3 2002
7 3 2003
8 3 2004
9 4 2002
10 4 2003
11 4 2004
12 4 2005
13 5 2001
14 5 2002
15 6 2001
16 6 2002

现在,我希望总结一年内退出市场的公司数量。例如,我想要一个这样的表:
 resulttable
All 2001 2002 2003 2004 2005
2001 3 0 2 0 1 0
2002 3 0 1 0 1 1

结果表第一行表示2001年有3家公司进入市场,2003年有2家公司退出,2004年有1家公司退出。谢谢!

最佳答案

您可以使用 table 将“进入”年份和“退出”年份制成表格:

res <- table(
dt$year[!duplicated(dt$firm)],
factor(dt$year[!duplicated(dt$firm, fromLast = TRUE)], levels = unique(dt$year))
)
res <- as.data.frame.matrix(res)
res$All <- rowSums(res)

# > res
# 2001 2002 2003 2004 2005 All
# 2001 0 2 0 1 0 3
# 2002 0 1 0 1 1 3

我假设了 dt按规定排序。如果不是,则必须首先按年份排序。

这是来自 thelatemail 的评论中的建议方式,结果如下所示:
addmargins(table(
dt$year[!duplicated(dt$firm)],
factor(dt$year[!duplicated(dt$firm, fromLast = TRUE)], levels = unique(dt$year))
), 2)

# 2001 2002 2003 2004 2005 Sum
# 2001 0 2 0 1 0 3
# 2002 0 1 0 1 1 3

关于r - 总结一年内的公司数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47256927/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com