gpt4 book ai didi

stata - 选择数据集中的多项选择

转载 作者:行者123 更新时间:2023-12-04 08:27:03 24 4
gpt4 key购买 nike

原始数据包含有关 consumerid 的信息和 cars他们purchased .

clear
input consumerid car purchase
6 American 1
6 Japanese 0
6 European 0
7 American 0
7 Japanese 0
7 European 1
7 Korean 1
end
由于这是一个购买数据,因此需要以某种方式扩展数据集,以在消费者每次购买时描述完整的汽车选择集。最终的数据集应如下所示(取自 Stata 手册 www.stata.com/manuals/cm.pdf 第 97 页的“示例 4:每个案例的多项选择”中的屏幕截图):
enter image description here
我已经生成了几个代码(如下所示)几乎可以让我到达我需要的地方,但是我无法为每个消费者 ID-车号组合生成一个购买值=1(即由于扩展,购买值重复)。
egen sumpurchase=total(purchase), by(id)
expand sumpurchase
bysort id car (purchase): gen carnumber=_n



最佳答案

您可以使用 reshape获取每辆车购买的消费者 ID/汽车的所有组合。此示例假设原始数据集中的排序顺序定义了汽车编号 1、汽车编号 2 等。

* Example generated by -dataex-. To install: ssc install dataex
clear
input byte consumerid str8 car byte purchase
6 "American" 1
6 "Japanese" 0
6 "European" 0
7 "American" 0
7 "Japanese" 0
7 "European" 1
7 "Korean" 1
end

// Generate carnumber
bys consumerid: gen carnumber = cond(purchase != 0, sum(purchase), 0)

// To wide
reshape wide purchase, i(consumerid car) j(carnumber)

// Keep purchased cars only
drop purchase0

// Back to long
reshape long

// Drop if no cars purchased for consumerid/carnumber
bysort consumerid carnumber (purchase) : drop if missing(purchase[1])

// Replace missing with 0 for non-purchased cars
mvencode purchase, mv(0)

// Sort and see results
sort consumerid carnumber car
list, sepby(consumerid carnumber) abbr(14)
结果:
. list, sepby(consumerid carnumber) abbr(14)

+----------------------------------------------+
| consumerid car carnumber purchase |
|----------------------------------------------|
1. | 6 American 1 1 |
2. | 6 European 1 0 |
3. | 6 Japanese 1 0 |
|----------------------------------------------|
4. | 7 American 1 0 |
5. | 7 European 1 1 |
6. | 7 Japanese 1 0 |
7. | 7 Korean 1 0 |
|----------------------------------------------|
8. | 7 American 2 0 |
9. | 7 European 2 0 |
10. | 7 Japanese 2 0 |
11. | 7 Korean 2 1 |
+----------------------------------------------+

关于stata - 选择数据集中的多项选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65207985/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com