r - rbind lists to data.frame in for loop -
this (meaningless) truncated version of for-loop in r calculates land uses polygons. iterates nicely through data except when should bind calculations data.frame using plyr::rbind.fill()
. desired result (thes same number of) additional unwanted columns filled na-values (i guess has column names).
agri_coverage <- data.frame(matrix(rnorm(3), nrow=1)) set.seed(23) agri <- rnorm(10, 0.5) land_use <- null (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 }
what's best function/ method combine these lists 1 data frame , why these additional columns produced?
i tried other functions rbind()
, data.table::rbindlist()
without being successfull.
the reason getting additional unwanted columns filled nas because of fact list created in else
condition not named same list in if
condition. rbind.fill
appends columns same name onto each other , columns have different names filled na
. rbind.fill
help:
rbinds list of data frames filling missing columns na.
i think desired result can add line @ end of else condition:
names(wl) <- names(agri_coverage)
the code becomes:
land_use <- null (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)) names(wl) <- names(agri_coverage) } land_use <- rbind.fill(land_use, data.frame(wl)) #combine output }
which results in:
land_use x1 x2 x3 1 na na na 2 na na na 3 0.2182885 -1.046535 -0.2886886 4 0.2182885 -1.046535 -0.2886886 5 0.2182885 -1.046535 -0.2886886 6 0.2182885 -1.046535 -0.2886886 7 na na na 8 0.2182885 -1.046535 -0.2886886 9 na na na 10 0.2182885 -1.046535 -0.2886886
Comments
Post a Comment