如何聚合两列,同时创建一个计算聚合的新列?

发布于 2025-01-16 21:24:00 字数 376 浏览 7 评论 0原文

我有这些数据

col1   col2
A      1
A      2
A      1
A      2
A      2
B      1
B      2
B      1
B      2
B      1

,我需要按 col1 和 col2 进行聚合,同时创建 col3,这很重要:

col1   col2   col3
A      1      2
A      2      3
B      1      3
B      2      2

我尝试了聚合函数,但它要求我使用现有列之一来应用该函数,并且我无法添加第三个列柱子。 我尝试在两列中使用 unique,但后来我没有得到 col3。

I have this data

col1   col2
A      1
A      2
A      1
A      2
A      2
B      1
B      2
B      1
B      2
B      1

And I need to aggregate by col1 and col2, while creating col3, that counts:

col1   col2   col3
A      1      2
A      2      3
B      1      3
B      2      2

I tried aggregate function, but it requires me to use one of the existing columns to apply the function to and I couldn't add the third column.
I tried using unique across the two columns, but then I don't get col3.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

许久 2025-01-23 21:24:00

我们可以使用count

library(dplyr)
df1 %>% 
   count(col1, col2, name = 'col3')

We may use count

library(dplyr)
df1 %>% 
   count(col1, col2, name = 'col3')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文