import multiple files R

≯℡__Kan透↙ 提交于 2019-12-13 03:43:55

问题


I hope you can help me. I have been trying to import multiple raster datasets into R, recode missing values for each raster data imported, link them to zipcodes and then export each raster data as a csv file with different names. I am trying to use a loop but so far I have only got errors. This is as far as I have gotten (dont laugh):

import all 24 raster datasets

file_names=as.list(dir(pattern="home.*"))
listy<-lapply(file_names,raster, band=1)
names(listy) <- paste0("hour", seq_along(0:23))

so now I have all the raster datasets in a list (listy) and I just need to run the following commands on each one:

example for element 1 of listy

listy$hour1_r<-listy$hour1
listy$hour1_r[listy$hour1_r==9999]<-NA
y <- extract(listy$hour1_r, zipcoords)
hour1_zipcode <- cbind(zipid,y)
write.table(hour1_zipcode,file="home\\hour1.csv",sep=",",row.names=F)

How can I do this with a loop? I would very much appreciate any suggestions that you may have!

Thank you!!! m


回答1:


Make a function out of your commands:

f <- function(listy,filename) {
  listy$hour1_r<-listy$hour1
  listy$hour1_r[listy$hour1_r==9999]<-NA
  y <- extract(listy$hour1_r, zipcoords)
  hour1_zipcode <- cbind(zipid,y)
  write.table(hour1_zipcode,file=filename,sep=",",row.names=F)
}

Run your command on all elements:

mapply(f, listy, filename= paste0("home\\hour",seq_along(listy),".csv"))

Note that you don't actually want mapply to return anything, so you could wrap it in invisible:

invisible(mapply(f, listy, filename= paste0("home\\hour",seq_along(listy),".csv")))

You could also do this in a for loop:

filenames = paste0("home\\hour",seq_along(list),".csv")
for (i in seq_along(listy)) f(listy[[i]],filenames[[i]])



回答2:


cant you just do it in a for loop?

for(i in 1:length(listy)) { 

listy[[i]] <- listy[[i]]
etc
}     

or with lapply

lapply(listy, function(x) { 
  x[[i]] <- x[[i]]
  etc
  } 
)


来源:https://stackoverflow.com/questions/19575224/import-multiple-files-r

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