我有一些35,000行。如果preventtive_chem值爲「Y」,則prev_efficacy的值在過去3天爲5,3,1,在下一週爲10到1。樣例輸出在img文件中。R for循環,爲新變量賦值增量值
Prev_Chem Date prev_effi
0 7/3/2016 0
0 7/4/2016 0
0 7/5/2016 1
0 7/6/2016 3
Y 7/7/2016 5
0 7/8/2016 10
0 7/9/2016 9
0 7/10/2016 8
0 7/11/2016 7
0 7/12/2016 6
0 7/13/2016 5
0 7/14/2016 4
0 7/15/2016 3
0 7/16/2016 2
0 7/17/2016 1
0 7/18/2016 0
0 7/19/2016 0
如果preventive_chem值爲0,則prev_efficacy值爲0
當我嘗試這個代碼,
*df$PreventEffic <- rep(0,nrow(df))
for(i in 1:nrow(df))
{
if(df$Preventive_Chem1[i] == "Y")
{
df$PreventEffic[i] <- 5
df$PreventEffic[i-2] <- 1
df$PreventEffic[i-1] <- 3
df$PreventEffic[i+1] <- 10
df$PreventEffic[i+2] <- 9
df$PreventEffic[i+3] <- 8
df$PreventEffic[i+4] <- 7
df$PreventEffic[i+5] <- 6
df$PreventEffic[i+6] <- 5
df$PreventEffic[i+7] <- 4
df$PreventEffic[i+8] <- 3
df$PreventEffic[i+9] <- 2
df$PreventEffic[i+10] <- 1
}
}*
這將需要大量的時間來運行代碼和返回值0到1016321行。有沒有有效的方法來處理這個問題,而不使用「for循環」。
將來,請始終輸入您的樣本數據,例如'dput(df)',這樣我們就可以複製和粘貼你的數據,但在這之前,請修復與命名約定不一致的地方 - 爲什麼你的if語句中df的colname不同? 'Prev_Chem'與'Preventive_Chem1'。我在下面提供解決方案。 – Djork
我們是否需要考慮數字分配之間的任何重疊?也就是說,是否會有Prev_Chem的+10和-3範圍內出現2個Y的事件? – JPHwang
Teenu Ss,我強烈建議你接受@ R.S.的回答,但考慮一下'Y'的晚期角落案例,作爲我的回答和評論。 – r2evans