[英]Translating Stata Loop
I'd like to translate the following Stata loop to R:我想将以下 Stata 循环转换为 R:
foreach day of numlist 1/7 {;
replace dywt = 1/7 * 1/Freq[`day',1] if interview_day==`day';
}
Data (R Output):数据(R 输出):
> INTERVIEW_DAY[1:15]
[1] 5 6 6 4 4 4 1 2 6 4 6 7 6 3 6
> Freq
[1] 0.14353969 0.14795762 0.14089618 0.14074198 0.14194271 0.14295769 0.14196413
> F
[1] 20720
> DYWT[1:15]
[1] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
Thank you in advance.先感谢您。
In R
, if all of them are vector
s, then the equivalent would be to just replace the NA
vector ('DYWT') by getting corresponding 'Freq' for each sequence value of 'INTERVIEW_DAY' ( Freq[INTERVIEW_DAY]
- as INTERVIEW_DAY
is a sequence of numeric vector which can be used as position vector for 'Freq'), divide by 1, and multiply with 1/max(INTERVIEW_DAY)
在R
如果它们都是vector
s,则相当于是只更换NA
通过获取相应的“频率”关于“INTERVIEW_DAY”的每个序列值向量(“DYWT”)( Freq[INTERVIEW_DAY]
-作为INTERVIEW_DAY
是一个数字向量序列,可用作 'Freq') 的位置向量,除以 1,然后乘以1/max(INTERVIEW_DAY)
DYWT <- 1/max(INTERVIEW_DAY) * 1/Freq[INTERVIEW_DAY]
Or if it is based on the number of unique elements, it can be also或者如果是基于唯一元素的数量,也可以
DYWT <- 1/length(unique(INTERVIEW_DAY)) * 1/Freq[INTERVIEW_DAY]
or it is 1/7
where 7
is the number of unique elements in 'INTERVIEW_DAY' (if some of the index are missing, then it may be better to use 1/7
)或者它是1/7
,其中7
是 'INTERVIEW_DAY' 中唯一元素的数量(如果缺少某些索引,那么使用1/7
可能更好)
INTERVIEW_DAY <- scan(text = '5 6 6 4 4 4 1 2 6 4 6 7 6 3 6', what = integer())
Freq <- scan(text = '0.14353969 0.14795762 0.14089618 0.14074198 0.14194271 0.14295769 0.14196413', what = numeric())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.