首页 > 解决方案 > 使用 R 按组创建基于另一个变量的最大值的二进制变量

问题描述

我想创建一个新的二进制列 ( choice),它在变量Uby的最大值中取第一,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. U首先,我遍历行(这是缓慢的部分)以获得by的最大值id_choice
  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)

结果,例如,第一个个体(前三个观察值)在等于choice时得到一个数字 1 。第二个人在等于时获得数字 1 ,以此类推。U0.912405259choiceU1.777680828

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),但代码的描述部分确实很耗时,因为它是使用循环观察编写的,我知道这很重要建议不要这样做,这就是为什么我想问是否有人可以提出一种矢量化的方式来执行此操作。提前谢谢了!

标签: raggregatevectorizationlapply

解决方案


您可以尝试以下方法:

  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

推荐阅读