Unique body count column

≯℡__Kan透↙ 提交于 2021-02-05 07:10:32

问题


I'm trying to add a body count for each unique person. Each person has multiple data points.

df <-  data.frame(PERSON  = c("A", "A", "A", "B", "B", "C", "C", "C", "C"),
                  Y = c(2, 5, 4, 1, 2, 5, 3, 7, 1))

This is what I'd like it to look like:

  PERSON Y UNIQ_CT
1      A 2       1
2      A 5       0
3      A 4       0
4      B 1       1
5      B 2       0
6      C 5       1
7      C 3       0
8      C 7       0
9      C 1       0

回答1:


You can use duplicated and negate it:

transform(df, uniqct = as.integer(!duplicated(Person)))



回答2:


Since there is dplyr tag to the question here is an option

library(dplyr)

df %>% 
   group_by(PERSON) %>% 
   mutate(UNIQ_CT = ifelse(row_number( ) == 1, 1, 0))


来源:https://stackoverflow.com/questions/35348926/unique-body-count-column

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!