使用 R 按组创建基于另一个变量的最大值的二进制变量

Creating a binary variable based on the maximum of another variable by group using R

我想创建一个新的二进制列 (choice),它在变量 U 的最大值中取一个数 id_choice,在其他情况下取零。

以此样本数据为例:

 sample_df <- structure(list(id = c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L), altern = c(1L,2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L), time = c(0.60622924522549, 0.685763204423431,1.04445466206904, 2.0823687526597, 0.470385492467578, 0.278410094130233,4.3933007737356, 1.30150082775573, 0.164433239189492), cost = c(0.775815897061855,3.65632847698275, 0.853480119066832, 4.18372276257574, 0.386247047617908,0.0499751011513356, 0.50605264042165, 0.309115653465334, 1.63340498409165), id_choice = c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L), U = c(-0.384172837567259,0.912405259429594, -0.00977885942620305, -1.82630532041359, -0.228713211633138,1.77768082832823, -1.7172001044961, -0.0197827158096625, 0.3408726361911)), row.names = c(NA, 9L), class = "data.frame") 

id altern      time      cost id_choice            U
1  1      1 0.6062292 0.7758159         1 -0.384172838
2  1      2 0.6857632 3.6563285         1  0.912405259
3  1      3 1.0444547 0.8534801         1 -0.009778859
4  2      1 2.0823688 4.1837228         2 -1.826305320
5  2      2 0.4703855 0.3862470         2 -0.228713212
6  2      3 0.2784101 0.0499751         2  1.777680828
7  3      1 4.3933008 0.5060526         3 -1.717200104
8  3      2 1.3015008 0.3091157         3 -0.019782716
9  3      3 0.1644332 1.6334050         3  0.340872636

目前,我所做的是以下几行:

  1. 首先,我遍历行(这是缓慢的部分)以通过 id_choice 获得 U 的最大值。
  2. 其次,我使用 ifelse 生成二进制变量以识别选择了哪个选项。
# First: Geting the maximum value of utility (U)
for (i in 1:max(sample_df$id_choice)) {
  sample_df$choice[sample_df$id_choice==i]<-which.max(sample_df$U[sample_df$id_choice==i])
}

# Second: Generating the binary output for the choice decision
sample_df$choice<-ifelse(sample_df$altern==sample_df$choice,1,0)

因此,例如,当 U 等于 0.912405259 时,第一个人(前三个观察值)在 choice 中获得数字 1。当 U 等于 1.777680828 时,第二个人在 choice 中获得数字 1,等等

id altern      time      cost id_choice            U choice
1  1      1 0.6062292 0.7758159         1 -0.384172838      0
2  1      2 0.6857632 3.6563285         1  0.912405259      1
3  1      3 1.0444547 0.8534801         1 -0.009778859      0
4  2      1 2.0823688 4.1837228         2 -1.826305320      0
5  2      2 0.4703855 0.3862470         2 -0.228713212      0
6  2      3 0.2784101 0.0499751         2  1.777680828      1
7  3      1 4.3933008 0.5060526         3 -1.717200104      0
8  3      2 1.3015008 0.3091157         3 -0.019782716      0
9  3      3 0.1644332 1.6334050         3  0.340872636      1

附带说明一下,我正在为 运行 一些模拟生成数据以估计多项式 logit(或条件 logit),但是代码的描述部分非常耗时,因为它是使用循环观察,我知道强烈建议不要这样做,这就是为什么我想问问是否有人可以想出一种矢量化的方式来执行这个操作。非常感谢!

您可以尝试以下方法:

  id_choice_split <- split(sample_df$U,sample_df$id_choice)
  sample_df$choice <- unlist(lapply(id_choice_split, function(uValues) as.numeric(uValues == max(uValues))))
  sample_df