How to split a data frame by rows, and then process the blocks?

后端 未结 7 1176
北荒
北荒 2020-12-08 17:32

I have a data frame with several columns, one of which is a factor called \"site\". How can I split the data frame into blocks of rows each with a unique value of \"site\",

7条回答
  •  春和景丽
    2020-12-08 18:16

    You can use isplit (from the "iterators" package) to create an iterator object that loops over the blocks defined by the site column:

    require(iterators)
    site.data <- read.table("isplit-data.txt",header=T) 
    sites <- isplit(site.data,site.data$site)
    

    Then you can use foreach (from the "foreach" package) to create a plot within each block:

    require(foreach)
    foreach(site=sites) %dopar% {
     pdf(paste(site$key[[1]],".pdf",sep=""))
     plot(site$value$year,site$value$peak,main=site$key[[1]])
     dev.off()
    }
    

    As a bonus, if you have a multiprocessor machine and call registerDoMC() first (from the "doMC" package), the loops will run in parallel, speeding things up. More details in this Revolutions blog post: Block-processing a data frame with isplit

提交回复
热议问题