我有一个数据集,如下所示:
clear
input year price growth id
2008 5 -0.444 1
2009 . . 1
2010 7 -0.222 1
2011 9 0 1
2011 8 -0.111 1
2012 9 0 1
2013 11 0.22 1
2012 10 0 2
2013 12 0.2 2
2013 . . 2
2014 13 0.3 2
2015 17 0.7 2
2015 16 0.6 2
end
我想生成变量growth
,它是price
的增长。增长公式为:
growth = price of second-year - price of base year / price of base year
基准年始终为2012
。
如何为每个观察组(通过growth
)生成此id
变量?
答案 0 :(得分:2)
以下对我有用:
bysort id: generate obs = _n
generate double wanted = .
levelsof id, local(ids)
foreach x of local ids {
summarize obs if id == `x' & year == 2012, meanonly
bysort id: replace wanted = (price - price[`=obs[r(min)]']) / ///
price[`=obs[r(min)]'] if id == `x'
}
如果id
的值是连续的,则以下操作会更快:
forvalues i = 1 / 2 {
summarize obs if id == `i' & year == 2012, meanonly
bysort id: replace wanted = (price - price[`=obs[r(min)]']) / ///
price[`=obs[r(min)]'] if id == `i'
}
结果:
list, sepby(id)
+-----------------------------------------------+
| year price growth id obs wanted |
|-----------------------------------------------|
1. | 2008 5 -.444 1 1 -.44444444 |
2. | 2009 . . 1 2 . |
3. | 2010 7 -.222 1 3 -.22222222 |
4. | 2011 9 0 1 4 0 |
5. | 2011 8 -.111 1 5 -.11111111 |
6. | 2012 9 0 1 6 0 |
7. | 2013 11 .22 1 7 .22222222 |
|-----------------------------------------------|
8. | 2012 10 0 2 1 0 |
9. | 2013 12 .2 2 2 .2 |
10. | 2013 . . 2 3 . |
11. | 2014 13 .3 2 4 .3 |
12. | 2015 17 .7 2 5 .7 |
13. | 2015 16 .6 2 6 .6 |
+-----------------------------------------------+
答案 1 :(得分:2)
基本价格可以直接由func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let frame = CGRect(x: 0, y: 0, width: view.frame.width, height: 50)
let dummyCell = Cell(frame: frame)
let targetSize = CGSize(width: view.frame.width, height: 1000)
let dummyData = data[indexPath.row]
dummyCell.data = dummyData
dummyCell.layoutIfNeeded()
let height = max(MINIMUM_CELL_SIZE,
dummyCell.systemLayoutSizeFitting(targetSize).height)
return CGSize(width: view.frame.width, height: height)
}
选择:
egen
请注意,使用bysort id: egen price_b = total(price * (year == 2012))
generate wanted = (price - price_b) / price_b
的假设是,对于每个total
,您只有一个观察到id
的情况。