我有一个具体的问题. 我有一个在R中看起来像这样的数据集:
name person_id year municipality_id
<chr> <dbl> <dbl> <dbl>
1 Brown 654 2000 1
2 Brown 781 2000 1
3 James 2531 2000 1
4 Smith 2187 2000 1
5 Smith 6 2000 1
6 White 22 2000 45
7 Colgan 100 2000 45
8 Brown 45123 2000 45
9 Smith 11 2000 45
10 Smith 9 2000 45
11 Brown 654 2004 1
12 Brown 1641 2004 1
13 James 2531 2004 1
14 Smith 2187 2004 1
15 Smith 450 2004 1
16 White 42 2004 45
17 Colgan 100 2004 45
18 Brown 45123 2004 45
19 Smith 11 2004 45
20 Smith 86573 2004 45
21 Brown 654 2008 1
22 Brown 1641 2008 1
23 James 2531 2008 1
24 Smith 2187 2008 1
25 Smith 450 2008 1
26 White 42 2008 45
27 Colgan 100 2008 45
28 Brown 45123 2008 45
29 Smith 11 2008 45
30 Smith 86573 2008 45
我想知道每个城市有多少不同的人在同一年或前一年有相同的名字.
换句话说,我想要创建一个列(n_same
),它给出每个组municipality_id
中的行数,这些行数在同一年或前几年中具有相同值name
,但不同值person_id
.然后是一个值为0/1的列,这取决于n_same
是否== 0(值为0)或不是(1).
结果基本上是这样的:
name person_id year municipality_id n_same dummy
<chr> <dbl> <dbl> <dbl> <dbl> <dbl>
1 Brown 654 2000 1 1 1
2 Brown 781 2000 1 1 1
3 James 2531 2000 1 0 0
4 Smith 2187 2000 1 1 1
5 Smith 6 2000 1 1 1
6 White 22 2000 45 0 0
7 Colgan 100 2000 45 0 0
8 Brown 45123 2000 45 0 0
9 Smith 11 2000 45 1 1
10 Smith 9 2000 45 1 1
11 Brown 654 2004 1 2 1
12 Brown 1641 2004 1 2 1
13 James 2531 2004 1 0 0
14 Smith 2187 2004 1 2 1
15 Smith 450 2004 1 2 1
16 White 42 2004 45 1 1
17 Colgan 100 2004 45 0 0
18 Brown 45123 2004 45 0 0
19 Smith 11 2004 45 2 1
20 Smith 86573 2004 45 2 1
21 Brown 654 2008 1 2 1
22 Brown 1641 2008 1 2 1
23 James 2531 2008 1 0 0
24 Smith 2187 2008 1 2 1
25 Smith 450 2008 1 2 1
26 White 42 2008 45 1 1
27 Colgan 100 2008 45 0 0
28 Brown 45123 2008 45 0 0
29 Smith 11 2008 45 2 1
30 Smith 86573 2008 45 2 1
我已经try 了一堆不同的东西在这一点上,不能真正得到它.任何帮助是非常感谢.谢谢!