我有一個示例data.frame(df
,下面),其中包含三個時間步長的變量值(大小)sz_t1
,sz_t2
,sz_t3
。變量t1_t2
,t2_t3
,t1_t3
是是否個體(ID
)從時間步「存活」的二進制指示符1 - 2,2 - 3,或1 - 3按行,將第一個時間步移到第一個非零列(滯後),然後創建新變量
代替使用時間步的,我想以「年齡」作爲時間單位。也就是說,使用每個ID的第一個非零值作爲起點。例如,如果sz_t1
爲零,則t1_t2
將被記錄爲NA
,但如果sz_t1
爲零,但使用「年齡」,但sz_t2
大於零,則可以使用零或一個生存結果記錄age1_2
。所以,如果我用這個age
移位的時間單位,我也想知道在那個年代(sz_age1
等)的值(大小)
將R下面的代碼使用ifelse
語句來實現示例數據所期望的結果。框架(df
)。然而,隨着時間步數的增加,我覺得可能會有一個不太詳細的或者更簡潔的方法來實現我所尋求的結果。隨着更多時間步驟的增加,我不確定我能否掌握ifelse
連鎖店。
我試圖找到基於第一個非零列索引的信息創建組,然後將這些組落後於適當的值。但是,我沒有找到辦法做到這一點,至少不是廣泛的格式,或者是每組不同的滯後。
是否有另一個r軟件包或命令可以實現這些結果以努力減少鏈接長度ifelse
?
df <- structure(list(ID = 1:5, sz_t1 = c(0.5, 0.25, 0, 0, 0.25), sz_t2 = c(0.6,
0.25, 0.25, 0.55, 0), sz_t3 = c(0, 0.35, 0.35, 0, 0)), .Names = c("ID",
"sz_t1", "sz_t2", "sz_t3"), class = "data.frame", row.names = c(NA,
-5L))
# did the id 'survive' from t1 to t2, etc
df$t1_t2 <- ifelse(df$sz_t1 > 0, ifelse(df$sz_t2 >0,1,0), NA)
df$t2_t3 <- ifelse(df$sz_t2 > 0, ifelse(df$sz_t3 >0,1,0), NA)
df$t1_t3 <- ifelse(df$sz_t1 > 0, ifelse(df$sz_t3 >0,1,0), NA)
# "age"
# did the id 'survive' from age1 to age2, etc
df$age1_2 <- ifelse(df$sz_t1 > 0, ifelse(df$sz_t2 >0,1,0),
ifelse(df$sz_t2 > 0, ifelse(df$sz_t3 >0,1,0), NA))
# if zero in first time step, age 2 to age 3 is NA as this time has yet to elapse
df$age2_3 <-ifelse(df$age1_2 > 0, ifelse(df$sz_t1 > 0,
ifelse(df$sz_t2 > 0, ifelse(df$sz_t3 > 0,1,0),NA),NA),NA)
# for the moment this is the same as df$t1_t3, need a t1 to get a value for age1_3, otherwise NA as the this time period has yet to elapse
df$age1_3 <- ifelse(df$sz_t1 > 0, ifelse(df$sz_t3 >0,1,0), NA)
# what was the size at the ages
df$sz_age1 <- ifelse(df$sz_t1 > 0, df$sz_t1, df$sz_t2)
df$sz_age2 <- ifelse(df$sz_t1 > 0, df$sz_t2, df$sz_t3)
df$sz_age3 <- ifelse(df$sz_t1 > 0, df$sz_t3, NA)
請不要使用您未使用的軟件包進行標記,只是爲了吸引回答。我在談論'data.table'和'plyr'。 – Frank
「t1_t3」列是否真的有必要?只需再增加一個時間步,如果你需要的話,比如't1_t4','t2_t4','t3_t4',爲第t個時間步添加't-1'個新列,將會變得混亂。使用單個時間列(或者可能是開始時間和停止時間列),單個年齡列(開始時的年齡)和單個生存列,而不是試圖將[時間和年齡]在一個列組中以及另一個列組中的[時間和先前時間]。 – Gregor
經過進一步反思,'t1_t3'列不是必需的。我現在會考慮你的其他建議。 – nofunsally