On Thu, Jan 6, 2011 at 5:41 PM, stephen sefick <ssef...@gmail.com> wrote: > #Is there a way to break the below zoo object into non-NA data frames > algorithmically > #this is a small example of a much larger problem. > #It is really no even necessary to have the continuous chunks > #end up as zoo objects but it is important to have them end > #up with the index column. > #thanks for all of your help in advance, and > #if you need anything else please let me know > > library(zoo) > > ind. <- 1:200 > data <- c(1:50, rep(NA, 50), 1:50, rep(NA, 50)) > > z <- zoo(data, ind.) >
Below c(TRUE, diff(is.na(z)) != 0) gives a logical vector which is TRUE at the first position of any run of NAs or non-NAs. The cumsum of that gives a vector the same length as z such that each position of the first run is 1, each position of the second run is 2, etc. The NA runs are then set to 0 in the second line. In the third line we split z on g and drop the portion that corresponds to the NAs. > g <- cumsum(c(TRUE, diff(is.na(z)) != 0)) > g[is.na(z)] <- 0 > split(z, g)[-1] $`1` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 $`3` 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 141 142 143 144 145 146 147 148 149 150 41 42 43 44 45 46 47 48 49 50 This could be combined into a multivariate series like this: do.call("merge", split(z, g)[-1]) -- Statistics & Software Consulting GKX Group, GKX Associates Inc. tel: 1-877-GKX-GROUP email: ggrothendieck at gmail.com ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.