r - 向 df 添加一列以计算另一列中某个值的出现次数

标签 r add calculated-columns find-occurrences multiple-occurrence

我想做的是按“位置”添加一列,计算整个列“id”中的 id 出现次数:

 id <- c(204850, 204850, 204850,312512,312512,452452,285421,758412,758412,758412)
places <- c("kitchen","kitchen","garden","salon","salon","salon","bathroom","garden","bathroom","garden")
 df <- data.frame(id, places)
 

    > df
           id   places
    1  204850  kitchen
    2  204850  kitchen
    3  204850   garden
    4  312512    salon
    5  312512    salon
    6  452452    salon
    7  285421 bathroom
    8  758412   garden
    9  758412 bathroom
    10 758412   garden

我看到的唯一选项是在 dplyr 中按计数,但它是创建一个新的数据框。

输出应该是这样的:

> df
       id   places id_occurrence
1  204850  kitchen             3
2  204850  kitchen             3
3  204850   garden             3
4  312512    salon             2
5  312512    salon             2
6  452452    salon             1
7  285421 bathroom             1
8  758412   garden             3
9  758412 bathroom             3
10 758412   garden             3

最佳答案

您可以使用以下解决方案:

library(dplyr)

df %>%
  group_by(id) %>%
  add_count(name = "id_occurrence")

# A tibble: 10 x 3
# Groups:   id [5]
       id places   id_occurrence
    <dbl> <chr>            <int>
 1 204850 kitchen              3
 2 204850 kitchen              3
 3 204850 garden               3
 4 312512 salon                2
 5 312512 salon                2
 6 452452 salon                1
 7 285421 bathroom             1
 8 758412 garden               3
 9 758412 bathroom             3
10 758412 garden               3

关于r - 向 df 添加一列以计算另一列中某个值的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67900302/

相关文章:

python - rpy2 - 如何将数据帧作为 RData 文件保存到磁盘?

python - 无损添加或合并python字典

sql - 当行可以包含 0 时计算百分比

sql-server - 在计算列中使用 master.sys.fn_varbintohexsubstring

r - 从非常大的边列表中快速计算单向、双向链接的数量

r - 在数据框中的两个日期之间生成日期

Python pandas 数据框添加前一行值

MySQL 虚拟列和通配符

r - 使用 R 在数据框中生成随机缺失值

c# - 为什么我的列表框没有被填充?