新浪博客

Stata技巧 - 使用subinstr()计算子串的数量

2015-06-15 11:58阅读:
问题描述:计算一篇论文中作者的数量;
数据描述:核心变量为Author,如果有多个作者的,中间用逗号分隔。
数据形式如下:
ID Author
1 H Taras, M Zive, P Nader, CC Berry, T Hoy, C Boyd
2 C Preston
3 BZ Erdogan, MJ Baker
... ...


决思路:1.将问题转化为计数Comma的个数,然后加1得到作者数量。
2.Stata中没有直接计算子串个数的函数,但可以配合使用字符串函数实现。
a. 将待计数子串全部替换为空串
b. 原字符串长度减去新字符串长度即为子串个数
Stata 代码:
gen AuthorNum = strlen(Author) - strlen(subinstr(Author,',','',.)) + 1








参考
Cox, Nicholas J. 'Stata tip 98: Counting substrings within strings.' Stata Journal 11, no. 2 (2011): 318.
原文链接

我的更多文章

下载客户端阅读体验更佳

APP专享