通过ID,唯一展开多列

By ID, uniquely expanding multiple columns

假设我有这个数据集。

id  headquarter_name    subsidiary_name
A     Apple                 Apple
A     Apple Inc.            Apple
A     Apple Computer        Apple corp.
B     Microsoft             MS
B     MS                    MS

为了您的方便,我创建了这个数据集 here

我想为每个 ID 创建一个像这样广泛分布的 "unique" 个名称的列表。

id   Name1        Name2         Name3          Name4
A    Apple      Apple Inc.  Apple Computer   Apple corp.
B    Microsoft     MS

它必须是唯一的。 "Apple" 多次出现,但仅包含一次,例如。

为了做到这一点,我唯一能想到的就是到目前为止,这当然不是我想做的。

collapse (first) headquarter_name subsidiary_name,by(id)
clear
input str1 id  str42 ( headquarter_name    subsidiary_name) 
A     "Apple"                 "Apple"
A     "Apple Inc."            "Apple"
A     "Apple Computer"        "Apple corp."
B     "Microsoft"             "MS"
B     "MS"                    "MS"
end 
stack id headquarter_name id subsidiary_name, into(id name) clear 
drop _stack
duplicates drop
bysort id (name) : gen which = _n
reshape wide name, i(id) j(which)
list 

     +--------------------------------------------------------+
     | id   name1            name2        name3         name4 |
     |--------------------------------------------------------|
  1. |  A   Apple   Apple Computer   Apple Inc.   Apple corp. |
  2. |  B      MS        Microsoft                            |
     +--------------------------------------------------------+

对此的一个变体将在删除重复项之前添加按提及频率排序。