考虑以下数据集:
df = data.frame(id = c(1,1,1,2,2,2,3,3,3),
time = c(1,2,3,1,2,3,1,2,3),
x = c(8,8,9,7,7,7,7,7,8),
id_x = c(1,1,2,3,3,3,4,4,5))
Run Code Online (Sandbox Code Playgroud)
我想在R中(最好使用dplyr)计算变量id_x,该变量标识变量id和的每个唯一组合x。
在Stata中,我可以执行以下操作:
clear
input id time x
1 1 8
1 2 8
1 3 9
2 1 7
2 2 7
2 3 7
3 1 7
3 2 7
3 3 8
end
egen id_x = group(id, x)
list, separator(0)
+----------------------+
| id time x id_x |
|----------------------|
1. | 1 1 8 1 |
2. | 1 2 8 1 |
3. | 1 3 9 2 |
4. | 2 1 7 3 |
5. | 2 2 7 3 |
6. | 2 3 7 3 |
7. | 3 1 7 4 |
8. | 3 2 7 4 |
9. | 3 3 8 5 |
+----------------------+
Run Code Online (Sandbox Code Playgroud)
我们可以使用dplyr::group_indices:
library(dplyr)
#df1 %>% mutate(id_xx = group_indices(.,id,x))
df1 %>% group_by(id,x) %>% mutate(id_xx = group_indices())
#> # A tibble: 9 x 5
#> # Groups: id, x [5]
#> id time x id_x id_xx
#> <dbl> <dbl> <dbl> <dbl> <int>
#> 1 1 1 8 1 1
#> 2 1 2 8 1 1
#> 3 1 3 9 2 2
#> 4 2 1 7 3 3
#> 5 2 2 7 3 3
#> 6 2 3 7 3 3
#> 7 3 1 7 4 4
#> 8 3 2 7 4 4
#> 9 3 3 8 5 5
Run Code Online (Sandbox Code Playgroud)
df1 <- data.frame(id = c(1,1,1,2,2,2,3,3,3),
time = c(1,2,3,1,2,3,1,2,3),
x = c(8,8,9,7,7,7,7,7,8),
id_x = c(1,1,2,3,3,3,4,4,5))
Run Code Online (Sandbox Code Playgroud)