stata - 非连续高度变量的变换
问题描述
我无法有效地转换样本中错误编码的高度变量。
变量编码如下:
Height
ID1 601
ID1 601
ID1 601
ID3 409
ID3 410
ID4 511
. .
. .
. .
ID100 400
如您所见,变量同时编码为英尺和英寸,其中601
等于 6 英尺 1 英寸,511
等于 5 英尺 11 英寸等。
我的目标是将这些数字转换为英寸:
replace Height = 48 if Height == 400
replace Height = 49 if Height == 401
replace Height = 50 if Height == 402
replace Height = 51 if Height == 403
.
.
.
replace Height = 83 if Height == 611
如何使用循环有效地编写代码?
解决方案
下面的代码假设每个观察值Height
恰好包含三个数字:
tostring Height, generate(Height_string)
/* Generate a new variable which is a string-version of Height
(so that we can get the individual digits) */
generate feet = substr(Height_string, 1, 1)
/* From the first character in the string, select one character */
generate inch = substr(Height_string, 2, 2)
/* From the second character in the string, select two characters.
An equivalent alternative would have been
generate inch = substr(Height_string, -2, 2)
which from the second to last character selects two characters */
destring feet inch, replace
/* Convert these two new variables to numeric */
generate tot_inch = feet * 12 + inch
/* Generate a new variable which measure only in inches. */
推荐阅读
- ruby-on-rails - Rails 数据确认提交的参数作为对话框的一部分
- module - 我多次安装 pyaudio 但无法正常工作?错误:无法卸载“PyAudio”
- ethereum - Eth rollup 或 Plasma 可以与锁定的以太坊执行交易吗
- node.js - 在前端应用程序中隐藏 api 密钥
- hololens - 使用全息远程播放器应用程序,我总是只看到一个带有“正在接收...”文本的黑屏
- redis - Redis 数组同步问题(lpop、rpush)
- c# - 有人可以帮我吗?我无法获得正确的输出,我尝试多次更改公式,但仍然无法
- struct - 我收到“已读取 ScrollView contentOffset 绑定”警告
- android - Android-Jetpack-Compose @Composable 注解错误
- javascript - 更改 div 显示时提交的表单