我的数据如下
library(tibble)
df <- tibble(ID = c(100000L, 100000L, 100000L, 100000L, 100001L, 100001L, 100001L, 100001L, 100002L, 100002L, 100002L, 100002L, 100003L, 100003L, 100003L), subject_result2 = c("OTHERPassedTerm1", "OTHERPassedTerm1", "OTHERPassedTerm1", "MATHPassedTerm1", "OTHERPassedTerm1", "OTHERPassedTerm1", "OTHERPassedTerm1", "OTHERFailedTerm1", "OTHERPassedTerm1", "OTHERPassedTerm1", "MATHPassedTerm1", "MATHFailedTerm1", "OTHERPassedTerm1", "MATHPassedTerm1", "OTHERPassedTerm1"))
# A tibble: 15 x 2
ID subject_result2
<int> <chr>
1 100000 OTHERPassedTerm1
2 100000 OTHERPassedTerm1
3 100000 OTHERPassedTerm1
4 100000 MATHPassedTerm1
5 100001 OTHERPassedTerm1
6 100001 OTHERPassedTerm1
7 100001 OTHERPassedTerm1
8 100001 OTHERFailedTerm1
9 100002 OTHERPassedTerm1
10 100002 OTHERPassedTerm1
11 100002 MATHPassedTerm1
12 100002 MATHFailedTerm1
13 100003 OTHERPassedTerm1
14 100003 MATHPassedTerm1
15 100003 OTHERPassedTerm1
我想基于每个subject_result2
获得一个唯一的ID
。如下所示,但此代码不起作用
library(dplyr)
df %>%
group_by(ID) %>%
distinct(subject_result2)
您能解决我的问题吗?谢谢
所需结果:
# <int> <chr>
#1 100000 OTHERPassedTerm1
#2 100000 MATHPassedTerm1
#3 100001 OTHERPassedTerm1
#4 100001 OTHERFailedTerm1
#5 100002 OTHERPassedTerm1
#6 100002 MATHPassedTerm1
#7 100002 MATHFailedTerm1
#8 100003 OTHERPassedTerm1
#9 100003 MATHPassedTerm1
答案 0 :(得分:2)
您只需要做
distinct(df)
# A tibble: 9 x 2
# ID subject_result2
# <int> <chr>
#1 100000 OTHERPassedTerm1
#2 100000 MATHPassedTerm1
#3 100001 OTHERPassedTerm1
#4 100001 OTHERFailedTerm1
#5 100002 OTHERPassedTerm1
#6 100002 MATHPassedTerm1
#7 100002 MATHFailedTerm1
#8 100003 OTHERPassedTerm1
#9 100003 MATHPassedTerm1
答案 1 :(得分:1)
您可以做的一件事是计算ID和subject_result2组合的实例。
new_df <- df %>%
group_by(ID, subject_result2) %>%
summarise(id = n()) %>%distinct() %>%
select(-id)
new_df