[英]Convenient way of defining a list as observation in a data.frame
有沒有一種方法可以在循環內部定義“觀察列表”? 例如,只要在data.frame的另一個觀察滿足特定條件時,我就可以運行以下代碼來替換每個“觀察為列表”,例如下面的代碼,但是我需要將lists
創建為一組NULL
lists
在運行循環之前。 另外,我還沒有弄清楚如何將list
放置在創建data.frame
的行中—有辦法嗎?
這是代碼:
#line that creates the data.frame: I wished to know how to place the list
#(at the line after creating the data.frame object) inside the data.frame function.
df = data.frame(x=1:10)
#line that creates the list as NULL values before replacing them in the loop
df$y = list(c())
#random replacement condition
df$z = c(0,0,1,0,1,0,1,0,0,0)
#Loop: could I create the list variable on the run without creating it before the loop?
for(i in 1:10) {
if (df$z[i]==1) {
df$y[i] = list(c("a","b"))
}
}
如果遵循某些原則(例如,整潔)有更先進的技術或推薦的方法,那么如果有人可以參考它,我將非常高興。
我不確定為什么要這樣做,但是可以將代碼減少為
df <- data.frame(x = 1:10, z = c(0,0,1,0,1,0,1,0,0,0))
df$y <- ifelse(df$z == 1, list(c("a","b")), list())
它會給出相同的結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.