rbind data.frames with same number of columns but different number of rows in a for loop, exactly one bellow another (vertically)

点点圈 提交于 2020-01-17 09:05:57

问题


I have read a lot of data.frame rbind related questions, but none of them helped my situation. I have made a script to recursively scan folders, extract pixel values from each image in the folder based on the shapefiles, with the help of a for loop. In the picture attached you can see the data.frame which is a result of this extraction from one folder. pixel extraction dataframe

All the other folders have the same number of images which are very similarly named, so the number of columns in the other dataframes will always be the same and the columns will match, but the number of rows will be different for some other reason. I do not care about the names of the columns from new images, I literally just want to vertically paste the results of the extraction for each folder. Rbind gives me "names do not match previous names" error, rbind.fill puts the new columns horizontally as does the merge function.

Here is the code, it has some prerequisite steps and steps related to my local folder structure which are not neccessary for the question but it will not hurt to show it I guess. Sorry cause its messy, I am not very experienced in R:

dirs=list.dirs(full.names=TRUE)
dirs=dirs[grepl("R20",dirs)]
dirs=as.list(dirs)
dirs

DataToWrite=list()
for (j in 1:length(dirs)) {

   setwd(paste("E:/SUO-
PUO/Ostalo/Sentinel/Potencijalna_rjesenja/R/",as.character(dirs[j]),sep="/"))
   files=list.files(full.names=FALSE,pattern="*20m*.tif$")
   for (i in 1:length(files)) {

      curRaster=raster(paste(getwd(),files[i],sep="/"))
      rasterOut=(na.omit(extract(curRaster,azo_plohe, cellnumbers=TRUE, 
      weights=TRUE, df=TRUE)))
      DataToWrite=c(DataToWrite,rasterOut[3])
      }

   mylist=as.data.frame(DataToWrite)
   naziv_fajla=as.vector(rep((substr((names(DataToWrite)
   [1]),5,19)),nrow(mylist)))
   tablica_folder=as.data.frame(c(rasterOut[2],naziv_fajla[1],mylist))
   }

This code, though certainly not the best way to do such a task, is OK for one folder, but when it starts to loop another and gets to the part where it needs to combine them ("mylist=as.data.frame(DataToWrite)") i get this error:

"Error in (function (..., row.names = NULL, check.rows = FALSE, check.names = 
TRUE, : arguments imply differing number of rows: 100, 63"

Can anyone help me?

来源:https://stackoverflow.com/questions/47041205/rbind-data-frames-with-same-number-of-columns-but-different-number-of-rows-in-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!