英文:
Randomly assign the value of a variable within a group
问题
我想要在R中为每个id_group中的id_individual随机分配值0或1。每个组由两个个体组成,随机变量应满足以下条件(在一个组内):sum(random_var)==1。
更具体地说,我希望我的随机变量如下所示:
ID_GROUP | ID_INDIVIDUAL | Random_var |
---|---|---|
1 | 1 | 1 |
1 | 2 | 0 |
2 | 1 | 0 |
2 | 2 | 1 |
有没有办法在R中编写这个请求的代码?
谢谢!
Chloé
英文:
I would like to randomly assign (in R) for each id_individual within an id_group the value 0 or 1. Each group is composed of two individuals and the random_var should respect the following condition (within a group) : sum(random_var)==1.
More precisely, I would like my random var be like :
ID_GROUP | ID_INDIVIDUAL | Random_var |
---|---|---|
1 | 1 | 1 |
1 | 2 | 0 |
2 | 1 | 0 |
2 | 2 | 1 |
Any idea how to code this request in R?
Thanks!
Chloé
答案1
得分: 3
你可以在 ave
内部尝试使用 sample
> transform(df, Random_var = +(ave(ID_INDIVIDUAL, ID_GROUP, FUN = sample) == 1))
ID_GROUP ID_INDIVIDUAL Random_var
1 1 1 0
2 1 2 1
3 2 1 1
4 2 2 0
英文:
You can try sample
within ave
> transform(df, Random_var = +(ave(ID_INDIVIDUAL, ID_GROUP, FUN = sample) == 1))
ID_GROUP ID_INDIVIDUAL Random_var
1 1 1 0
2 1 2 1
3 2 1 1
4 2 2 0
答案2
得分: 2
使用`dplyr`中的`group_by`选项如下:
``` r
library(dplyr)
df %>%
group_by(ID_GROUP) %>%
mutate(Random_var = sample(0:1))
#> # A tibble: 4 × 3
#> # Groups: ID_GROUP [2]
#> ID_GROUP ID_INDIVIDUAL Random_var
#> <int> <int> <int>
#> 1 1 1 0
#> 2 1 2 1
#> 3 2 1 1
#> 4 2 2 0
2023-05-26使用 reprex v2.0.2创建
<details>
<summary>英文:</summary>
`dplyr` option using `group_by` like this:
``` r
library(dplyr)
df %>%
group_by(ID_GROUP) %>%
mutate(Random_var = sample(0:1))
#> # A tibble: 4 × 3
#> # Groups: ID_GROUP [2]
#> ID_GROUP ID_INDIVIDUAL Random_var
#> <int> <int> <int>
#> 1 1 1 0
#> 2 1 2 1
#> 3 2 1 1
#> 4 2 2 0
<sup>Created on 2023-05-26 with reprex v2.0.2</sup>
答案3
得分: 2
以下是带有自定义函数的解决方案:
my_binary <- function(n) {
vec <- rep(0, n)
if(n == 1) {
vec <- sample(c(0, 1), 1)
} else {
vec[sample(n, 1)] <- 1
}
return(vec)
}
library(dplyr)
df %>%
group_by(ID_GROUP) %>%
mutate(Random_var = my_binary(n()))
ID_GROUP ID_INDIVIDUAL Random_var
<dbl> <dbl> <dbl>
1 1 1 0
2 1 2 1
3 2 1 0
4 2 2 1
数据:
df <- data.frame(
ID_GROUP = c(1, 1, 2, 2),
ID_INDIVIDUAL = c(1, 2, 1, 2)
)
英文:
Here is a solution with a custom function:
my_binary <- function(n) {
vec <- rep(0, n)
if(n == 1) {
vec <- sample(c(0, 1), 1)
} else {
vec[sample(n, 1)] <- 1
}
return(vec)
}
library(dplyr)
df %>%
group_by(ID_GROUP) %>%
mutate(Random_var = my_binary(n()))
ID_GROUP ID_INDIVIDUAL Random_var
<dbl> <dbl> <dbl>
1 1 1 0
2 1 2 1
3 2 1 0
4 2 2 1
data:
df <- data.frame(
ID_GROUP = c(1, 1, 2, 2),
ID_INDIVIDUAL = c(1, 2, 1, 2)
)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论