我有一个销售交易数据集,如下所示:
id mode week pr choice y1 y2 y3
75440 1 1642 0 0 1 0 0
75440 2 1642 0 0 0 1 0
75440 3 1642 1 1 0 0 1
138704 1 1642 0 0 1 0 0
138704 2 1642 1 1 0 1 0
138704 3 1642 0 0 0 0 1
每个客户正在考虑3个替代方案,但必须只选择一个;
id是进行购买的客户的唯一客户ID,
模式是客户可用的所有产品选择(1,2,3)的列表,
周 - 购买发生的那一周,
pr是购买是在促销(1)还是不是(0)。
选择是客户的选择,
和y1,y2,y3指的是表示购买替代品的模式。
如果您查看客户75440和138704,他们分别在同一周内促销(pr = 1)购买了产品3和2。但是,现在,pr并没有抓住这两个产品实际上在特定周内推广的事实。当我想通过查找每个特定周的pr值来显示此产品通常在促销时,如何创建一个新变量pr1 = 0并将其替换为pr1 = 1,以便结果如下所示:
id mode week pr choice y1 y2 y3 pr1
75440 1 1642 0 0 1 0 0 0
75440 2 1642 0 0 0 1 0 1
75440 3 1642 1 1 0 0 1 1
138704 1 1642 0 0 1 0 0 0
138704 2 1642 1 1 0 1 0 1
138704 3 1642 0 0 0 0 1 1
谢谢!
答案 0 :(得分:3)
我认为这个问题不在话题,因为你只是要求代码。我(和其他一些用户)通常期望看到原始海报的一些编码尝试,以及为什么它不适合她的一些描述。前/后数据示例很好,但同样没有代表您尝试代码。类似的事情发生在这里:How to avoid duplication of a certain variable during alternative-specific data organization?。我会再次尝试帮助,但如果你继续以这种方式发帖,你必须考虑到你没有得到任何有用答案的风险。
您可以尝试以下内容:
clear all
set more off
*----- example data -----
input ///
id mode week pr choice y1 y2 y3
75440 1 1642 0 0 1 0 0
75440 2 1642 0 0 0 1 0
75440 3 1642 1 1 0 0 1
138704 1 1642 0 0 1 0 0
138704 2 1642 1 1 0 1 0
138704 3 1642 0 0 0 0 1
end
list, sepby(id)
*----- what you want -----
bysort mode week: egen pr1 = max(pr)
*----- list data -----
sort id mode week
list, sepby(id)
请参阅help egen
和help by
。后者是Stata的基础。另请参阅Nick Cox的Speaking Stata: How to move step by: step。
关于bysort varlist:
中变量的顺序:
通常,排序变量的顺序会影响结果。在这种情况下,它没有。您只计算每组的最大值,并且符合某些 varlist 的组将始终相同,无论顺序如何。下面的一些代码我希望对此有所帮助。 (我已经添加了cf
的支票,它会比较使用不同订单计算的两个数据集的所有变量。)
clear all
set more off
*----- example data -----
input ///
id mode week pr choice y1 y2 y3
75440 1 1642 0 0 1 0 0
75440 2 1642 0 0 0 1 0
75440 3 1642 1 1 0 0 1
138704 1 1642 0 0 1 0 0
138704 2 1642 1 1 0 1 0
138704 3 1642 0 0 0 0 1
75440 1 1643 0 0 1 0 0
75440 2 1643 0 0 0 1 0
75440 3 1643 1 1 0 0 1
138704 1 1643 0 0 1 0 0
138704 2 1643 1 1 0 1 0
138704 3 1643 0 0 0 0 1
75440 1 1641 0 0 1 0 0
75440 2 1641 0 0 0 1 0
75440 3 1641 1 1 0 0 1
138704 1 1641 0 0 1 0 0
138704 2 1641 1 1 0 1 0
138704 3 1641 0 0 0 0 1
end
list, sepby(id)
*----- see that (mode week) groups are same as (week mode) groups -----
sort mode week
list, sepby(mode week)
sort week mode
list, sepby(week mode)
*----- compute original -----
bysort mode week: egen pr1 = max(pr)
sort id mode week
list, sepby(id)
tempfile first
save "`first'"
*----- compute with modification -----
drop pr1
bysort week mode: egen pr1 = max(pr)
sort id mode week
list, sepby(id)
*----- check two databases -----
cf _all using "`first'" // if no output, all fine
同样的原则适用于三个或更多变量。