【问题标题】:count the number of times that a number appears计算一个数字出现的次数
【发布时间】:2024-01-09 00:17:02
【问题描述】:

我有这个缩小的数据框

ind;year;n
67;2016;1
76;2016;1
95;2016;2
171;2016;3
60;2017;1
73;2017;1
95;2017;3
171;2017;1
175;2017;1
60;2018;4
95;2018;7
96;2018;1
99;2018;1
171;2018;1
171;2019;2
172;2019;1
178;2019;1

我想计算每年出现的个人数量,不包括前几年出现的个人。 在这种情况下,它看起来像这样:

year       n
 2016      4
 2017      3
 2018      2
 2019      2

我用过这个,但不排除往年出现的那些

df %>%
  group_by(ind, year) %>%
  dplyr::summarise(totalcount =n())%>%
  group_by(year)%>%
  tally()

【问题讨论】:

  • 你的 gruping 应该排除 'ind'

标签: r count numbers cell


【解决方案1】:

这是base R中的一个选项

lst1 <- split(df$ind, df$year)
lst1[] <- lengths(Reduce(function(x, y) y[!x %in% y],
            split(df$ind, df$year), accumulate = TRUE))
setNames(stack(lst1)[2:1], c('year', 'n'))
#  year n
#1 2016 4
#2 2017 3
#3 2018 3
#4 2019 2

如果这涉及所有以前的“年份”

lst1 <- split(df$ind, df$year)
lst2 <- vector('list', length(lst1))
names(lst2) <- names(lst1)
lst2[[1]] <- length(lst1[[1]])
for(i in 2:length(lst1))  lst2[[i]] <- sum(!lst1[[i]] %in% 
               unlist(lst1[seq_len(i-1)]))
setNames(stack(lst2)[2:1], c('year', 'n'))
#  year n
#1 2016 4
#2 2017 3
#3 2018 2
#4 2019 2

或者带有dplyr 的选项,我们arrange 按'年',取distinct 行(假设在'年'内不会有任何重复的'ind'),然后使用@ 987654327@

library(dplyr)
df %>% 
    arrange(year) %>%
    distinct(ind, .keep_all = TRUE) %>% 
    select(-n) %>%
    count(year)
# year n
#1 2016 4
#2 2017 3
#3 2018 2
#4 2019 2

数据

df <- structure(list(ind = c(67L, 76L, 95L, 171L, 60L, 73L, 95L, 171L, 
175L, 60L, 95L, 96L, 99L, 171L, 171L, 172L, 178L), year = c(2016L, 
2016L, 2016L, 2016L, 2017L, 2017L, 2017L, 2017L, 2017L, 2018L, 
2018L, 2018L, 2018L, 2018L, 2019L, 2019L, 2019L), n = c(1L, 1L, 
2L, 3L, 1L, 1L, 3L, 1L, 1L, 4L, 7L, 1L, 1L, 1L, 2L, 1L, 1L)),
class = "data.frame", row.names = c(NA, 
-17L))

【讨论】:

    【解决方案2】:

    我们可以在每个year 的列表中获取所有ind。在total 中,我们每年创建累积的ind 值并计算唯一的ind,我们计算lengthsetdiff

    library(dplyr)
    library(purrr)
    
    df %>%
       group_by(year) %>%
       summarise(ind = list(ind)) %>%
       mutate(total = accumulate(ind[-n()], ~unique(c(.x, .y)), .init = list()), 
               n = map2_int(ind, total, ~length(setdiff(.x, .y)))) %>%
       select(year, n)
    
    
    # A tibble: 4 x 2
    #   year     n
    #  <int> <int>
    #1  2016     4
    #2  2017     3
    #3  2018     2
    #4  2019     2
    

    数据

    df <- structure(list(ind = c(67L, 76L, 95L, 171L, 60L, 73L, 95L, 171L, 
    175L, 60L, 95L, 96L, 99L, 171L, 171L, 172L, 178L), year = c(2016L, 
    2016L, 2016L, 2016L, 2017L, 2017L, 2017L, 2017L, 2017L, 2018L, 
    2018L, 2018L, 2018L, 2018L, 2019L, 2019L, 2019L), n = c(1L, 1L, 
     2L, 3L, 1L, 1L, 3L, 1L, 1L, 4L, 7L, 1L, 1L, 1L, 2L, 1L, 1L)), 
     class = "data.frame", row.names = c(NA, -17L))
    

    【讨论】:

      最近更新 更多