2组计数指标

时间:2019-08-03 11:59:53

标签: r dataframe

我有一个小组,每个小组都有人。和一个指标。如何为每个人元素的每个组计算指标?

     group  person   ind
       1       1      1
       1       1      1
       1       2      1
       2       1      0
       2       2      1
       2       2      1

输出    因此,第一组中有2个人有ind,第二组中有一个人

      group  person   ind.   count  
       1       1      1        2
       1       1      1        2
       1       2      1        2
       2       1      0       1
       2       2      1        1
       2       2      1        1

2 个答案:

答案 0 :(得分:2)

可以做到:

library(dplyr)

df %>%
  group_by(group) %>%
  mutate(
    count = n_distinct(person[ind == 1])
  )

输出:

# A tibble: 6 x 4
# Groups:   group [2]
  group person   ind count
  <int>  <int> <int> <int>
1     1      1     1     2
2     1      1     1     2
3     1      2     1     2
4     2      1     0     1
5     2      2     1     1
6     2      2     1     1

或在data.table中:

library(data.table)

setDT(df)[, count := uniqueN(person[ind == 1]), by = group]

答案 1 :(得分:1)

使用c++ cmake_minimum_required (VERSION 3.5) project (StrVec) set(LIBRARY_TARGET_NAME ${PROJECT_NAME}) SET (CMAKE_CXX_COMPILER "/usr/bin/g++") set(${LIBRARY_TARGET_NAME}_SRC class.cpp ) set(${LIBRARY_TARGET_NAME}_HDR class.h ) add_library(${LIBRARY_TARGET_NAME} SHARED ${${LIBRARY_TARGET_NAME}_SRC}) SET(CMAKE_CXX_FLAGS "-g -O0 --coverage -fprofile-arcs -ftest-coverage") add_executable(main main.cpp) target_link_libraries(main StrVec --coverage)

的选项
base R