根据另一个变量的条件计算观察值

时间:2021-02-24 02:52:33

标签: r count sum

我有区域专利数据集。我想数一数Appln_id有多少个Person_id,有多少Appln_id只有一个Person_id。

    public IActionResult ProductIndex(string type)
    {
        //get all the initial data from the repository
        var productlist = _repo.GetProductViewModels();

        //based on the type to filter data.
        if (!string.IsNullOrEmpty(type) && type != "all")
        {
            productlist = productlist.Where(c => c.ProductType == type).ToList();
        }

        //set select items for the DropDownList
        ViewBag.Types = _repo.GetProductViewModels().Select(c=>c.ProductType).Distinct().ToList().Select(c => new SelectListItem { Text = c, Value = c }).ToList();
        return View(productlist);
    }

这里 Appln_id 3 有三个不同的 person_id (23,22,24) 而 Appln_id 2 只有一个 Person_id(101)。所以,我想数一数Appln_id有多少个Person_id,有多少Appln_id只有一个Person_id

2 个答案:

答案 0 :(得分:0)

为每个 Appln_id 计算唯一人的数量。

library(dplyr)
result <- df %>% group_by(Appln_id) %>% summarise(n = n_distinct(Person_id))
result

#  Appln_id     n
#*    <int> <int>
#1        2     1
#2        3     3
#3        4     2
#4       10     4

现在您可以计算其中有多少只有 1 Person_id 以及有多少有更多。

sum(result$n == 1)
#[1] 1

sum(result$n > 1)
#[1] 3

数据

df <- structure(list(Appln_id = c(3L, 3L, 3L, 10L, 10L, 10L, 10L, 2L, 
4L, 4L), Person_id = c(23L, 22L, 24L, 49L, 50L, 55L, 51L, 101L, 
122L, 104L)), class = "data.frame", row.names = c(NA, -10L))

答案 1 :(得分:0)

我们可以使用data.table

library(data.table)
setDT(df)[, .(n = uniqueN(Person_id)), by = Appln_id]