簡體   English   中英

循環列表以在 R 中分配名稱不起作用

[英]Loop over list to assign names in R not working

我有一堆行,我要添加到一個更大的數據框,稱為更大的_false。 我想使用 for 循環來做到這一點。 每一行看起來像這樣:

new_row1 <- c(402, 1, "false alarm", 0)

我想為較大數據框的列的每個新行分配名稱,因此我循環遍歷列表中的每一行並為每一行分配相同的名稱。

rowlist = list(new_row1, new_row2, new_row3, new_row4, new_row5, new_row6, new_row1011, new_row1014, new_row1016, new_row1022, new_row1023, new_row2021, new_row3046)

for (item in rowlist) {
      names(item) <- c("guest_id", "sessionNum", "interactions.hitType", "n")
    }

然后我遍歷每個並將它們添加到大數據框,它已經有這些列名。

for (item in rowlist) {
      bigger_false <- rbind(bigger_false, item)
    }

現在,第一個循環似乎適用於第一行(它成功地分配了名稱)。 所以如果我手動做

bigger_false <- rbind(bigger_false, new_row1)

我沒有錯誤。 但是,第一個循環的其余部分沒有成功地為其余的行分配名稱,因此 rbind 循環在第一次迭代后給出錯誤:“參數 2 必須有名稱”。

為什么會這樣? 提前致謝。

item變量在 rowlist 上循環,但不會修改 rowlist 的內容。
嘗試:

new_row1 <- c(402, 1, "false alarm", 0)
new_row2 <- c(403, 2, "false alarm", 0)

rowlist = list(new_row1, new_row2)

for (item in 1:length(rowlist)) {
  names(rowlist[[item]]) <- c("guest_id", "sessionNum", "interactions.hitType", "n")
}

bigger_false <- NULL
for (item in rowlist) {
  bigger_false <- rbind( item, bigger_false)
}
bigger_false

     guest_id sessionNum interactions.hitType n  
item "403"    "2"        "false alarm"        "0"
item "402"    "1"        "false alarm"        "0"

除了循環,您還可以執行以下操作:

# creates a matrix
df <- do.call(rbind, rowlist)

# create a dataframe
df <- data.frame(df)
colnames(df) <- c("guest_id", "sessionNum", "interactions.hitType", "n")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM