r - R:不平衡面板,为独特的观察创建假人
问题描述
我有一个不平衡的面板数据(意味着在所有时间段都没有观察到某些人)。我想创建一个虚拟变量,如果在两个或多个时期观察到一个人,则取值为 1,否则取值为 0。有人能够做到这一点并可以向我解释吗?对不起,如果这个问题看起来有点“微不足道”。
我试过这个,但它创建了多个假人,我只需要一个。
for(level in unique(df$id)){
share[paste("dummy", level, sep = "_")] <- ifelse(df$id == level, 1, 0)
}
一个小例子可能是:
set.seed(123)
df <- data.frame(id = sample(1:10, 20, replace = TRUE),
happy = sample(c("yes", "no"), 20, replace = TRUE))
和预期的输出:
id happy dummy
3 no 1
8 no 0
5 no 1
9 no 1
10 no 1
1 no 1
6 no 1
9 no 1
6 yes 1
5 yes 1
10 no 1
5 no 1
7 no 0
6 no 1
2 yes 0
9 yes 1
3 no 1
1 yes 1
4 yes 0
10 yes 1
解决方案
使用dplyr
,您可以避免循环并尝试以下操作:
set.seed(123)
df <- data.frame(id = sample(1:10, 20, replace = TRUE),
happy = sample(c("yes", "no"), 20, replace = TRUE))
library(dplyr)
df <- df %>%
group_by(id) %>%
mutate(dummy = ifelse(length(id)>=2, 1, 0))
> df
# A tibble: 20 x 3
# Groups: id [10]
id happy dummy
<int> <fct> <dbl>
1 3 no 1
2 8 no 0
3 5 no 1
4 9 no 1
5 10 no 1
6 1 no 1
7 6 no 1
8 9 no 1
9 6 yes 1
10 5 yes 1
11 10 no 1
12 5 no 1
13 7 no 0
14 6 no 1
15 2 yes 0
16 9 yes 1
17 3 no 1
18 1 yes 1
19 4 yes 0
20 10 yes 1
本质上,这种方法除以df
的唯一值,id
然后创建一个列dummy
,如果该 id 出现两次以上,则值为 1,否则为 0。
推荐阅读
- vb.net - 为什么我的查询值和字段数不匹配?
- java - 在java中的每个单词之间添加空格
- sql - Gorm 在多对多插入中添加多个切片
- mule - 有没有办法过滤 mule 4 中的批量插入?
- forms - 是否可以使用 MVVM 构建 Wix/Wix# UI?
- c# - WPF DataGrid - 如何设置正确的 DataTrigger 绑定到单元格的数据源(而不是行的源)
- hangouts-chat - 谷歌环聊覆盖 ID
- javascript - 我如何使用 Firestore 读取我存储中的图片?
- python - 来自抓取迭代的 Python 嵌套列表不适合 Pandas 数据框
- delphi - 从多个来源捕获彩色控制台输出