0
這是一個(無意義的)截斷版本的R中的for-loop,用於計算某些多邊形的土地使用情況。它很好地遍歷數據,除非它應該使用plyr::rbind.fill()
將計算綁定到data.frame。我得到了期望的結果,但也有(相同數量的)其他不需要的列填充了NA值(我想它與列名有關)。rbind列表到for循環中的data.frame
agri_coverage <- data.frame(matrix(rnorm(3), nrow=1))
set.seed(23)
agri <- rnorm(10, 0.5)
land_use <- NULL
for (i in seq_along(agri)) {
name <- agri[i]
if (name > 1) {
wl <- as.list(unlist(agri_coverage[ ,1:3]))
} else {
wl <- as.list(rep(NA, 3))
}
land_use <- rbind.fill(land_use, data.frame(wl)) #combine output
}
什麼是最好的功能/方法將這些列表合併爲一個數據框,爲什麼這些額外的列產生?
我試過其他功能,如rbind()
,data.table::rbindlist()
沒有成功。
'rbind.fill'(和它的dplyr後繼'bind_rows')尋找同樣的na mes爲每個矢量對齊它們,而你的'NA's沒有名字。如果你把'else'改成'wl < - as.list(setNames(rep(NA,3),names(agri_coverage)))',它就會起作用。更典型的基本方法是'do.call(rbind,lapply(agri,function(x){if(x> 1){agri_coverage} else {rep(NA,3)}}))' – alistaire
我正在想辦法複雜化。感謝您的解釋! – andrasz