Changelog
Source:NEWS.md
drawn (development version)
Wrong answers, fixed
-
Reordering, subsetting or binding a weighted sample gave wrong standard errors. The sample matched its rows to the frame by position, so a sort moved each row onto another row’s stratum, cluster or systematic position. Sorting one stratified sample by
ycut its standard error from 3,015 to 1,332, andhead(),s[cond, ]andrbind()were estimated as if drawn. Each row now finds its frame row through the new.rowcolumn, so reordering by[,dplyr::arrange()ordata.table::setorder()changes nothing, andht_total(),ht_mean(),as_svydesign()andsample_summary()refuse a subset, a sample bound to another, or a join that repeats rows. A sample saved by drawn 0.2.0 has no.rowcolumn and is still matched by position, so it is refused once the frame columns it keeps show its rows in another order, unless a column with a different value in every frame row, such as an id, still matches them in order;as_drawn()rebuilds it with.row. -
Editing the frame in place after drawing changed the sample’s estimates. The sample kept a reference to the frame, so a data.table
setkey(),setorder()or:=on it afterwards changed the standard error, interval, degrees of freedom and design effect of a sample already drawn. In one examplesetkey()halved a cluster sample’s standard error; in anothersetorder()took a certainty sample’s design effect from 1.04 to 171.draw()now stores a copy of the frame, column names included, sosetnames(),setcolorder()or deleting a column with:=does not reach the sample either. -
A certainty design over a with-replacement
restwas weighted anyway.draw(weights = TRUE)checkedreplaceonly on the outer design, sodesign_certainty()overdesign_simple(replace = TRUE)ordesign_stratified(replace = TRUE)returned duplicates weighted as distinct units, and in one example a total a third too high. It is now refused like any other with-replacement design. Drawing it without weights is still allowed.ht_total(),ht_mean(),as_svydesign()andsample_summary()refuse such a sample saved by drawn 0.2.0. -
Renaming, recoding or dropping a design column in a sample changed its standard errors. The degrees of freedom, the jackknife,
as_svydesign()andsample_summary()read strata and cluster labels from the sample’s columns, while the analytic variance read them from the frame. Dropping a cluster sample’s cluster column set the degrees of freedom to 0, which removed the interval, and made the jackknife delete rows instead of clusters, 61% low in one example. Recoding stratum labels broke the jackknife andas_svydesign(), or gave them the wrong strata. Every path now reads design columns from the copy of the frame stored with the sample, so onlyyandbycome from the sample’s own columns, andas_svydesign()passes the clusters tosurveyin a.clustercolumn. -
A spatial sample analysed under another
sf::sf_use_s2()setting got the wrong standard error. Which rows lie inside the region was worked out again in the current session. A sample drawn undersf::sf_use_s2(FALSE), the documented workaround for a region that crosses the antimeridian, and analysed after switching back or afterreadRDS()in a new session got standard errors for a different region: 5.7 times too large in one example, and 0 with a zero-width interval in another. The point estimate was not affected.ht_total(),ht_mean(),as_svydesign()andsample_summary()now check that the design still gives the frame the inclusion probabilities it gave at draw time, and refuse the sample when it does not, namingsf::sf_use_s2()for a spatial design. That includes a design that now stops, such as one whosenis more than the rows inside the region under the current setting. A sample saved by drawn 0.2.0, which records no probabilities for the frame, is checked against its.probcolumn instead.?design_spatialsays the setting must be the same at draw time and after. -
The jackknife and the local-mean variance treated rows taken with certainty as random. A row that is in every possible sample was deleted, or compared with its neighbours, as if it could have been left out. With the units
design_weighted(method = "systematic")takes with certainty, the jackknife averaged 181 times the true variance on one frame, andvariance = "auto"fell back to it when one sampled row was below certainty.design_spread(size =)with dominant sizes averaged 1,270 times the true variance. Both estimators now hold certain units fixed, and the jackknife’s finite population correction counts only the other units. Its note says how many units it held fixed. With one unit below certainty the variance is reported as missing instead. -
A census got a nonzero jackknife or local-mean standard error.
variance = "jackknife"on a sample of every row or every cluster applied no finite population correction, giving 114 for a six-cluster census in one example, anddesign_spread()withnequal to the frame reported a standard error of about 5% of the exact total. Both now give 0, as the analytic estimators did. -
design_weighted()could give a certain unit a probability a rounding error below 1. Depending on the scale of the sizes, a unit whose share came to exactly 1 got1 - 1e-16, so.prob == 1missed it and a census reported a small standard error under a “Deville approximation” note. A share within1e-9of 1 is now taken with certainty at exactly 1, indesign_weighted()anddesign_spread(size =). -
A certainty design whose
restdrew no rows reported an exact total. When arestof random size, such as Poisson sampling with a smalln, drew none of the rows below the threshold,ht_total()andht_mean()gave a standard error of 0 and a zero-width interval although those rows went unobserved. The total is exact only when no row lies below the threshold. Otherwise the variance is now missing, with a note naming the rowsrestdid not reach. -
Units taken with certainty counted as degrees of freedom. The t intervals of
ht_total()andht_mean()counted every sampled unit, including the onesdesign_weighted()anddesign_spread(size =)take with certainty, strata anddesign_temporal()intervals taken whole, clusters taken whole by a two-stage design that selects every cluster, and such units inside a certainty design’srest. With eight certain units among ten, systematic PPS reported 9 degrees of freedom where the same selection built withdesign_certainty()had 1, and its interval covered 79%; a temporal design whose sparse days were taken whole covered 83%. Only units below certainty count now, and a stratum or interval holding none of them drops out. A sample with no unit below certainty hasdf = Inf, and a certainty design whoserestdrew nothing hasdf0. -
as_svydesign()left units taken with certainty insurvey’s Brewer stratum. Fordesign_weighted(method = "systematic"),design_spread(size =)and a certainty design over a systematic PPSrest,surveystill centred and scaled Brewer’s approximation over the certain units, which put its standard error at 23 timesht_total()’s on a frame with four dominant units. They now go tosurveyin a stratum of their own, taken whole, and the two standard errors agreed within 0.03% there. -
A blank stratum or cluster value broke stratified and multistage designs. An empty string, such as a blank field read from a file, was looked up by name, which never matches it.
inclusion_prob(),joint_prob()anddraw(weights = TRUE)stopped with “subscript out of bounds” for a stratified design or a certainty design over one. Neyman allocation read the blank stratum’s spread as 0 and, withmin_per_stratumof 1 or more, gave its rows to the other strata without a word. A multistage sample gotNAprobabilities, weights and totals, andsample_summary()gave a blank group anNAframe count. A blank value is now a key like any other, shown as(blank)in messages and summaries. -
Two strata could be counted as one. Several
stratacolumns were joined into one key with a carriage return between the values, so("x\ry", "z")and("x", "y\rz")made one stratum of two, and the allocation, the probabilities and the variance were all worked out over the merged stratum. Two numbers that print alike, such as0.3and0.1 + 0.2, were one stratum too. Keys are now built from each column’s integer codes, which cannot collide. -
A sample estimated under another collation could get the wrong standard error. Text strata and a text
order_bywere sorted by the session’s collation, which differs between the C locale of a server and the en_US locale of a desktop. Where two strata tied in the largest-remainder split, the extra row went to a different stratum in each, and a stratified sample drawn in one and estimated in the other got a standard error 5 times too large in one example. A systematic sample walked on text got the wrong neighbours for the successive-difference variance, andjoint_prob()gave 0 for pairs drawn together. Text is now sorted byte by byte, as in the C locale, in every session. -
Two cluster labels that print alike were one cluster.
0.3and0.1 + 0.2print the same, and the cluster variance,joint_prob()for cluster and multistage designs, and the jackknife compared cluster labels as text. Adesign_cluster()sample holding both got no variance, and two rows of the two clusters got the joint probability of rows in one cluster. A multistage sample got a Sen-Yates-Grundy variance built on those joint probabilities.design_multistage()also counted the two as one cluster of twice the size, so their rows got half their inclusion probability and twice their weight, which doubled their part of an estimated total. Clusters are now compared by integer codes everywhere. -
design_multistage()refused a factor cluster column with unused levels. An unused level counted as a cluster of no rows, soinclusion_prob(),sampling_weight(),joint_prob(),draw(weights = TRUE)andplot(type = "probability")stopped with a false “no closed-form inclusion probability”. Unused levels are now ignored, asdroplevels()would drop them. -
joint_prob()gaveNAfor a multistage row with no cluster. Withna_rm = TRUE, a row whose cluster label is missing is never drawn, so its joint probabilities are 0, asdesign_cluster()gives.design_multistage()gaveNA, which filled the default matrix over every row withNA. -
inclusion_prob()overstated the probabilities ofdesign_multistage(replace = TRUE). It gave(a / A) * m / N_h, the expected number of times a row is drawn, where the probability of drawing it at least once is(a / A) * (1 - (1 - 1 / N_h)^m). In one example, 3 draws from a cluster of 4 rows gave 0.375 against 0.289. A cluster smaller than the per-cluster take was refused as capped at its own size, which it is not with replacement.draw(weights = TRUE)refuses with-replacement designs, so no estimate used these figures. -
A Hajek mean over one primary sampling unit had a standard error of 0. A
bydomain with one sampled row, or with all its sampled rows in one cluster that stage one could have left out, and a Poisson sample of one row got a standard error of 0 and a zero-width interval labelled “analytic”, because the linearised residuals of a mean sum to zero inside the one unit.surveygives the same 0.ht_mean()now gives such a mean no standard error, with a note, unless every unit of the domain was taken with certainty, which makes it exact. Rows taken with certainty count as one unit, as the jackknife andas_svydesign()treat them, so a domain whose sampled rows were all certain gets no standard error either while the design could have drawn its other rows. In one systematic PPS example a domain sampled as its two certain rows got a zero-width interval, where the domain mean’s standard deviation over 1,500 draws was 3.4.?ht_totaladds that intervals for domains with few sampled rows cover less often thanlevelsays. A domain total, and theestimator = "ht"mean, keep the standard error of 0 their unbiased estimators give such a domain, with a note that says why the interval has no width. -
A systematic sample understated the variance when
intervaldid not divide the frame. The sample size is then random, 30 or 31 rows for 244 rows at an interval of 8, and successive differences cannot see what that adds to a total. A constantygot a standard error of 0, and a variable with a coefficient of variation of 0.02 got 0.04 of its true variance and an interval that never covered the truth.ht_total(), domain totals andht_mean(estimator = "ht")now add a term for the random size, and the note says so. The default Hajek mean was not affected. -
deff()measured a design against a simple random sample of the whole frame, rows it could never reach included. A total estimates over the rows with a probability above 0, so an equal-probability sample of 20 from the first 100 of 400 rows,design_reservoir(max_items = 100), reported a design effect of 0.05, “better than simple random sampling”, and a temporal window or a spatial region over part of the frame read low the same way. The simple random sample is now drawn from the rows the design can reach, assurveymeasures it, and that sample gets 1. A Horvitz-Thompson mean gets its total’s design effect.?deffsays so. -
A constant
ygot a design effect and a Hajek standard error made of rounding error. With unequal weights, a total’s design effect came out as1.36e+32, “worse than simple random sampling”, and the Hajek mean’s standard error as about1e-16, with a design effect that changed from seed to seed. A Hajek mean of aythat takes one value in every sampled row, overall or in abydomain, now has a variance of exactly 0, with a note, and the design effect of a constantyisNA. -
Rows a design drops were counted in its finite population correction.
as_svydesign()gavesurveythe frame’s row count as thefpcofdesign_systematic(na_rm = TRUE), and the jackknife counted every row of the frame fordesign_spread()anddesign_weighted()withna_rm = TRUE. Both now count the rows the design can reach, and agree with the same draw from the frame without the dropped rows. The standard errors moved by under 1% in the examples checked. -
Size measures whose total overflowed gave every row a probability of 0. Positive weights near
1e306sum toInf, sodesign_weighted()withmethod = "systematic"or"poisson"anddesign_spread(size =)gave every row a probability of 0 and drew empty samples without a word, and a certainty design over them took only the rows above its threshold. Such weights are now divided by the largest of them first. Weights with a finite total give the same probabilities, and the same rows for a seed, as before. -
joint_prob()treated a row given twice inrowsas two rows. The pair a repeated row made with itself got the joint probability of two different rows, 0.015 for a simple random sample of 30 from 240 where the row’s own probability is 0.125, andsimulate = TRUEgave it 0. It now gets the row’s own probability on both paths.rowsthat are not whole numbers are refused, where 1.7 was read as row 1. -
min_per_stratumbroke the allocation rule between the strata it did not raise. The rows a stratum needed to reach the floor were taken back one at a time from the others, whatever their shares, so those were no longer split in proportion to size, evenly or bysize * sd. Under Neyman allocation with a floor of 4, two large strata with spreads of 1 and 3 got 19 and 101 rows where the rule gives 35 and 85, and the variance of a total was 14% higher. The weights followed the rows drawn, so estimates were not biased, only less precise. A stratum is now held at its floor or its size and the rest ofnre-split by the rule over the others, as for a stratum taken whole, which under Neyman allocation is the split of least variance within those bounds. When taking whole every stratum with a Neyman share leaves rows over, strata whoseallocation_bydoes not vary share them in proportion to size, as when no stratum varies, where they were split evenly.min_per_clusterindesign_multistage()is applied the same way. -
design_temporal()withunit = "days"or"weeks"drifted off midnight after a daylight-saving change. Intervals were a fixed 86,400 or 604,800 seconds, so in a zone with clock changes every interval after the change started an hour off midnight. ADatecolumn then put two calendar days into one interval, which sharedper_intervalbetween them: ten days of New York dates from 7 March 2024 gave nine intervals, with 10 and 11 March in one, anddraw()returned nine rows. Days and weeks now step by calendar days in the design’s zone, so every interval starts at the clock time offromand lasts 23 or 25 hours across a change. Seconds, minutes and hours are still fixed durations, and?design_temporalsays so. -
design_temporal()placed aDatewhose midnight a daylight-saving change skips or repeats at the wrong instant. Where clocks jump from 00:00 to 01:00, as in Santiago, Cairo and Sao Paulo, theDatebecame 23:00 the day before and fell in the previous day’s or month’s interval, and the same day written as a string did not parse. Where midnight happens twice, as in the Azores, the instant depended on the rows beside it, so reversing the frame changed inclusion probabilities and totals. A frame holding 30 December 2011 in Samoa, a day the zone skipped, stopped every function with a base R error, even underna_rm = TRUE. ADate, and a string without an offset, now stands for the first instant of its day in the design’s zone: 01:00 where midnight is skipped, the first midnight where it repeats, and the start of the next day for a day the zone skipped. A string ending inZor an offset such as+01:00keeps the instant it names. drawn now needs lubridate 1.9.0 or later. -
design_temporal()withunit = "months"or"years"anchored on the 29th to the 31st ran into the next month. A window from 31 January had intervals starting on 2 March, 31 March, 1 May and 31 May, and one from 29 February by years started its intervals on 1 March in the years between leap years. Months and years are now added tofromitself, and a day the month lacks moves to its last day: 29 February, 31 March, 30 April, and 28 February in the years between leap years. -
A
regiongiven as a list of parts that together cover more than half the globe selected the rest of the globe.design_spatial()unioned the parts, and under spherical geometry the union of the two halves of a band from -60 to 60 degrees of latitude came back as the two polar caps and a strip 2 degrees wide. The parts are kept separate now, and a row inside any of them is inside the region. -
design_spread()never drew a row whose inclusion probability was below1e-9. The pivotal walk set such probabilities to 0 before it started, whileinclusion_prob()and the sample’s weights still gave them their value, so a Horvitz-Thompson total was biased by the whole of each such row’sy. Every row with a probability above 0 now takes part, however small, and only the rounding error in a pooled probability is settled to 0 or 1. -
design_reservoir()stopped reading a list at its firstNULLelement. A list was read as a stream, in whichNULLmarks the end, so the elements after aNULL, common in lists built from JSON or withlapply(), were never sampled, and nothing said so. A list’s length is known, sodraw()now picks positions in it as it does in a data frame. Every element is an item,NULLincluded, and the elements keep their names. -
design_bootstrap()renamed or dropped a duplicated column name. A data frame with two columns namedacame back withaanda.1, and a tibble lost the secondawithout a word. Both now come back as they went in, after.replicate, as with every other design. -
plan_size()used a proportion’s finite population correction for a mean or a total.n0 / (1 + (n0 - 1) / N)fits a proportion, whose variance has the divisorN. A mean’ssdhas the divisorN - 1, and the smallest size for it isn0 / (1 + n0 / N). Plans for a mean or a total were sometimes a row too large, and a margin thatN - 1rows meet was planned as a census. Withsd = 40andN = 10, a margin of 8.4 gave all 10 rows and called it a census, where 9 meet it. -
plan_size()added a row when dividing byresponsegave a whole number.21 / 0.7is30.000000000000004in floating point, so 21 rows at 70% response gave 31 to draw where 30 bring back 21, and withN = 30the plan said the frame was too small at that response rate. -
plan_size()took an estimate fromsurveypassed asdefffor the design effect.survey::svymean(~y, des, deff = TRUE)is a number underneath, the estimated mean, so the plan was inflated by the mean ofywithout a word.plan_size()now refuses any object other than the result ofht_mean()orht_total()by its class, and for asurveyestimate points tosurvey::deff(). A number marked withI()is still taken as a number. -
plot(type = "probability")on a frame larger thanmax_dotsleft out unreachable and take-all rows. It drew and summarised an evenly spaced subset of the rows, so rows with probability 0 or 1 between them were missing from the line, the count of unreachable rows and the range. On a 10,000-row frame with two unreachable rows, the subtitle gave a range of 0.0499 to 0.0501 and no unreachable row; with two take-all rows it gave a highest probability of 0.0883. The counts, the range and the mean now cover every row, rows taken with certainty are counted too, and abovemax_dotseach step covers a run of rows and passes through its lowest and highest probability. -
plot(type = "selection")on a frame larger thanmax_dotscould show none of a systematic sample. The evenly spaced subset of rows it drew fell in step with the sampling interval, sodesign_systematic(interval = 5)on 10,000 rows showed 0, 667 or 1,333 of the 4,000 rows shown as selected, depending on the start, where every start selects 2,000. Each dot now stands for a run of consecutive rows and is filled when any of them is selected, and the count under the title covers the whole frame.
Refusals and clearer errors
as_svydesign()andsample_summary()give the same reason asht_total()when a sample has lost its design, and all three name the steps that drop it (merge(), column selection,subset(),transform(),cbind()) and how to add fieldwork columns instead.The refusal of
weights = TRUEfor a with-replacement design, and?draw, gave the bias as “about 15%”. It is a factor of(n / N) / (1 - (1 - 1 / N)^n), about 5% atn = N / 10, 58% atn = Nand more beyond, applied within each stratum, and both now say so and give the per-stratum Hansen-Hurwitz form.ht_total(),ht_mean(),as_svydesign()andsample_summary()refuse a sample whose.probcolumn was removed, is not numeric, holds a value outside (0, 1], or differs from the probabilities recorded at draw time (for a sample saved by drawn 0.2.0, from the ones its design gives). A removed.probgave a total of 0, and a missing value gaveNAwith a note saying the jackknife had run. The message says that adjusted weights belong in.weight.ht_total()andht_mean()refuse an infinite orNaNy, with the count and the rows, instead of returning an infinite total or standard error. A variance that overflows is reported as missing, and the note no longer says the jackknife ran when it gave no figure.ht_total()andht_mean()warn, with classdrawn_weight_edited, when.weightis no longer1 / .prob. They use the design probabilities in.prob, whileas_svydesign()hands.weighttosurvey, so after a nonresponse adjustment the two gave different totals without a word.?ht_totaland?as_svydesignsay which column each uses.ht_total()andht_mean()warn, with classdrawn_grouped_df, when the sample is grouped withdplyr::group_by(), which they ignore, and give thebythat estimates per group.A
bycolumn that the sample does not have is named in the error.draw(weights = TRUE)refuses adesign_certainty()whoserestgives every row below the threshold a probability of 0, such as one withn = 0, because the weighted total would leave those rows out. Drawing without weights still gives the cut-off sample of the rows above the threshold.An error raised by a certainty design’s
restindraw()orinclusion_prob()now says which rowsrestwas given, as in “Inrest, applied to the 230 rows withwbelow 100”.restcounts only those rows, so its own message spoke of 230 rows on a frame of 240.design_multistage()refuses annsmaller thann_clusters,n = 0included, which selected clusters and then took no rows from some of them, and amin_per_clusterthatncannot cover acrossn_clusters, whichdraw()refused only later.draw()warns, with classdrawn_empty_cluster, when proportional allocation gives a selected cluster no rows, and names it.A multistage sample from a single cluster gets no variance, with the reason “A variance needs at least two clusters”, as a
design_cluster()sample does. The note blamed an unlucky sample for a Sen-Yates-Grundy estimate that is negative on every such sample, and a constantygot an exact variance of 0. When stage one takes every cluster, as from a frame of one cluster, each cluster’s rows are the units of the analytic estimator, so totals, means, ratios and domain means inside one cluster get the variance of a simple random sample within it. The jackknife still deletes whole clusters, so a domain mean, ratio, quantile or contrast inside one cluster gets no standard error from it.ht_mean(estimator = "ht")withbyrefuses a frame whosebycolumns are missing for some rows, which could be in any domain. Each domain’s total was divided by its frame rows with those left out, so a domain of 30 frame rows, 10 of them withbymissing, got a mean 1.5 times too large. The Hajek mean, the default, needs no domain sizes and is unaffected.An
allocation,method,unit,variance,estimator,targetortypeoutside its choices is refused with a message that names the argument, the value passed and the choices. The message frommatch.arg()named neither the argument nor the value.NULLgives the default, as it did. A missing cluster label is called a cluster label byinclusion_prob()as well as bydraw().ht_total()andht_mean()stop with the error when something fails inside a variance estimator, such as running out of memory. Every error was read as the estimator declining, sovariance = "auto"fell back to the jackknife and gave R’s message, “cannot allocate vector of size 244.1 Mb” in one example, as the reason. Only a decline, a condition of classdrawn_declined, leads to the jackknife now.inclusion_prob()andjoint_prob()raise that class where a design has no closed form.A variance too large to represent, from values of
y / .probabove about1e154, is reported as missing with a note to rescaley, whichever estimator ran, and the note says it once.variance = "jackknife"reportsmethod = "none"when the jackknife gives no figure, as for a systematic or Poisson sample, which is what?ht_totalsays. It reported"jackknife", inbytables too. Its note for strata with one unit names them, in the words the analytic estimator uses, where it read “needs two units per stratum as well” with nothing before it, sovariance = "auto"gives that reason once.A
dfbelow 1 is refused. It was accepted and the interval dropped without a word. When the design leaves 0 degrees of freedom, as a Poisson sample of one row does, the note says that, andprint()shows it. It blamed one unit per stratum, and was not printed beside an analytic standard error.inclusion_prob(),sampling_weight(),joint_prob()andplot(type = "probability")refuse a design thatdraw()refuses, with the same message. They answered for it: annof 300 from 240 rows gave every row 1.25 underdesign_simple(), and a census of 1s underdesign_stratified()and the systematic and Poisson methods ofdesign_weighted(); ann_clustersabove the clusters available gave probabilities above 1; and a window shorter than one interval, or a key missing in every row underna_rm = TRUE, gave every row 0. The same holds for annabove the rows inside a spatial region, for a region with none, and for therestof a certainty design, checked against the rows below its threshold.design_multistage()refuses annthat even its largestn_clustersclusters cannot hold, on both paths.The weights of
design_weighted(), and of a certainty design over it, must be numeric on every path.inclusion_prob(),joint_prob(),draw(weights = TRUE)andplot(type = "probability")took a column ofTRUEas weights of 1 and stopped with a misleading message on a factor or text one, wheredraw()refused all three. Every message about the weights names the column, and the one for a weight of 0 or below says to drop those rows from the frame, since every design that selects in proportion to size refuses them.?inclusion_proband?ht_meansaid such rows get a probability of 0.inclusion_prob(),sampling_weight(),joint_prob()and the successive-difference variance refuse adesign_systematic()whoseorder_bycolumn is not in the frame, asdraw()did. A misspeltorder_bygave every row a probability of 0.A missing coordinate under
design_spatial()is reported in the same words bydraw()andinclusion_prob(), naming the twocoordscolumns.design_stratified()accepts amin_per_stratumlarger than some strata whenncovers it. Without replacement such a stratum is taken whole, so the floor needs only its rows: 7 rows meet a floor of 2 over strata of 1, 1, 1 and 100 rows, where 8 were asked for. The message gives the number needed and says how many strata are taken whole.Neyman allocation refuses an infinite
allocation_byvalue, as it refused a missing one. The spread of a stratum holdingInfcame out asNaNand was read as none, so the stratum with the most extreme values was allocated no rows. Finite values large enough to overflowsd()split as the same values on a smaller scale do, and a stratum of small values beside them keeps its own spread.The warning for a stratum allocated no rows says when Neyman allocation gave it no share because
allocation_byis constant within it. It then suggestsmin_per_stratum = 1, since a largernreaches such a stratum only once every other stratum is taken whole.design_stratified()withn = 0no longer warns for every stratum.design_temporal()checks its zone and bounds when it is built.tzmust be a name fromOlsonNames(), andfromandtomust each be one date-time, date or string that parses, withtoafterfrom. Withouttz, a bound that names an instant (a date-time, or a string ending inZor an offset) paired with a clock time (a date, or a string without an offset) can fall in either order depending on the zone. Such a pair is refused when the design is built if it is a day or more out of order, which no zone’s offset can undo, and otherwise when the design is used, in the zone the window is laid out in. The message names the argument and gives its value. An unknown zone gave a raw CCTZ error from every function that used the design, and an unparseablefromreachedinclusion_prob()as “‘to’ must be a finite number”. The message for an unparseable timestamp in a string column lists the forms that are read, and aPOSIXctcolumn in a zone R does not know is named.draw(),inclusion_prob(),joint_prob()andplot()warn, with classdrawn_geodesic_edges, when an edge of a longitude/latituderegionindesign_spatial()passes more than 0.1 degrees (about 11 km) from the straight line between its corners on a flat map. Under spherical geometry each edge follows a great circle, so the top edge of a box from -50 to 50 degrees of longitude at latitude 30 reaches latitude 41.9, and rows that far outside the box as drawn were sampled without a word.The warning about an edge across the antimeridian has class
drawn_antimeridianand gives both readings, the short way across the antimeridian and the long way the longitudes span. It said the region was “much smaller than its coordinates suggest”, which is wrong for a region meant to cross the antimeridian.inclusion_prob(),joint_prob()andplot(type = "probability")give it as well asdraw(), andinclusion_prob(simulate = TRUE)gives it once, not once per simulated draw. An edge from -180 to 180 still gives it, since both ends lie on one meridian and a box between them encloses nothing. An edge along a pole, where every longitude meets, no longer does, so a cap around a pole closed along it draws without a warning.design_spatial()refuses aregionof points or lines, which enclose no area, and namessf::st_buffer(), orsf::st_collection_extract()for a geometry collection.draw()found no row inside such a region, or only rows lying on it.design_spatial()reprojects each member of a listregiontocrsbefore combining them, so members in different CRSs work. They were refused with “regionmust be an sf or sfc geometry, or a list of them, not list”, which blamed the type.With longitude/latitude coordinates,
design_spatial()refuses a latitude outside -90 to 90 or a longitude outside -180 to 360, whichsfonly warned about, and says the columns may be in (lat, lon) order or hold projected coordinates.The refusals of
inclusion_prob(), and ofsimulate = TRUEininclusion_prob()andjoint_prob(), fordesign_bootstrap(method = "block")said each row appearsn_replicates * n / nrow(data)times on average. Under the moving-block bootstrap the first and lastblock_length - 1rows appear less often, and the message now says so.design_systematic()given more than oneorder_bycolumn says how to walk by several: add a column of ranks built from them, such asorder(order(data$a, data$b, method = "radix")), and give its name.?design_systematichas an example. The message said only thatorder_bymust name a single column.deff()of abytable says that domain estimates carry no design effect, and points to the estimate withoutby. It said the table “must come from ht_total() or ht_mean()”, which it did, andsurvey’sdeff()returnedNULLwith a warning.A
bycolumn namedn,variance,se,ci_lower,ci_upperormethod, ortotalfor a total andmeanfor a mean, columns the table of domain estimates uses for its own values, is refused by name. The table’s column overwrote it, soby = "n"gave domains labelled by their counts.A
bytable whose columns were selected with[orsubset()prints as a plain data frame. It kept its class but lost the attributes its printout reads, andprint()stopped with “argument is of length zero”.ht_total()refuses a missingywith a message that gives the share of the weight the rows withymissing hold, which is about how low a total over the other rows would be, and points toht_mean(na_rm = TRUE),byand a weighting-class adjustment throughas_svydesign(). It said only how many values were missing.ht_mean()points tona_rm.plan_size()refuses anNbelow 1, and plans at mostfloor(N)rows, so an estimatedNsuch as 240.5 gives a wholenthatdraw()accepts. It returnedn = 240.5, whichdraw()refused, andn = 0forN = 0.5.plan_size()refuses amarginof 1 or more for a proportion, and says to give it as a proportion, such as0.05for 5 percentage points. A margin of 5 planned one row.plan_size()warns that it ignoressdgiven for a proportion andpgiven for a mean or a total, and whensdis missing andpis given its refusal suggeststarget = "proportion". Both were ignored without a word, andplan_size(margin = 0.03, p = 0.2)said only thatsdwas required.plan_size()refuses adeffofNAwith the reasondeff()gives one, a pilot without a variance estimate or with one value ofy, or a mean fromht_mean(na_rm = TRUE)withymissing in some rows, whose design effect, a domain’s, is not estimated. It said only thatdeffmust be a positive number.plan_size()plans a census when the size for an unbounded frame is too large for a number, and refuses it for an unboundedNwith a message namingmarginandlevel. It stopped with “missing value where TRUE/FALSE needed”, or returnedn = Inf.plot()checkspalette,mainandsubbefore it draws anything. An entry ofpalettethe plot does not use, such asacent, an entry without a name, aNULLentry, or a value that is not one colour is refused by name, and a named character vector such asc(accent = "red")is read as a list. A colour R did not know stopped the plot partway, with part of the page drawn, and a badsurfaceleft the margins changed for the next plot. A misspelt entry was ignored, and a named vector stopped with “is.list(val) is not TRUE”.maintakes one string, one expression, or a name or call such asquote(alpha). A number, which was drawn as text, is refused, so writemain = "5"formain = 5. So are an emptyexpression(), which stopped the plot partway, and an expression of two or more parts, which were drawn over each other.A message about an argument given a function, a name, an environment or a data frame names its class, as in “not a function”. A function or a name gave a warning from
is.na()as well, and a data frame stopped with “the condition has length > 1”.plot()refuses an argument in...that is not a graphical parameter, such assimulate, and names it. It was passed to the panel, where base graphics dropped it with a warning.plot()namesywhen the population is not a data frame, where it saiddata.plot(type = "map")names the two columns when no row has both coordinates, where base graphics stopped with “need finite ‘xlim’ values”.Messages that name a class put “an” before a vowel, as in “not an integer”, where they said “not a integer”.
draw(),inclusion_prob()andjoint_prob()refuse aseedoutside the integer range, such as2^31, and give the range.set.seed()stopped with “supplied seed is not a valid integer” after a coercion warning. A seed, count,levelordfgiven as text reads asthe string "1"in the message, where it read like the number 1.inclusion_prob()andjoint_prob()checkseedwithoutsimulate = TRUEtoo, where they ignored any value.draw(),inclusion_prob()andjoint_prob()given the design first and the data second say the two look swapped and how to call the function. They said only thatdesignmust come from a constructor.A design with no closed-form inclusion probability points to
inclusion_prob(data, design, simulate = TRUE). It said “pass simulate = TRUE” when raised bydraw(weights = TRUE)andplot(), neither of which takessimulate. A design with no closed-form joint probability points tojoint_prob(data, design, simulate = TRUE)as well, where most of those refusals did not mention it, except a bootstrap, whose simulation is refused.A design class of your own (see
?draw_design) is refused bydraw(weights = TRUE)and the exact probabilities with a message that points toinclusion_prob(simulate = TRUE), where it said “No inclusion probability method for design type”. A draw method that drops columns ofdatais refused by the simulations, which counted it as drawing nothing.
Behaviour changes
draw(weights = TRUE)adds a third column,.row, after.proband.weight. It holds the row ofdataeach sampled row came from. A frame that already has a.rowcolumn is refused, as one with.probor.weightis.A sample drawn from a data.table takes
:=without the “Invalid .internal.selfref” warning. data.table joinsSuggests.ht_total()of an empty sample from a design of random size, which Poisson sampling or a systematic start past the last row can give, returns a total of 0 with no variance and a note, where it stopped with an error. Over repeated draws that 0 is what keeps the total unbiased, so a simulation loop no longer has to catch it.ht_mean()refuses the Hajek mean of an empty sample, which is 0 / 0, and gives 0 forestimator = "ht". An empty sample from a design that reaches no row, such as one withn = 0, is still refused, and the message says so.?ht_totaldescribes this.Text keys are sorted byte by byte, as in the C locale, whatever the session’s locale: the order in which strata are drawn and in which they break allocation ties, the rows of
byestimates and ofsample_summary(), and the walk of a textorder_by. Text read from a file without a declared encoding, asread.csv()andreadLines()give it, is sorted by its bytes in the same way, Latin-1 read in a UTF-8 session included. An unmarked cluster label and a UTF-8 one with the same bytes are one cluster in every locale, as they are one stratum; in the C locale they were two. Factor columns keep their level order. In a locale whose collation differs from C, a seed can therefore select different rows than it did in drawn 0.2.0, and a tie can go to another stratum.?design_stratifiedgives the tie rule.byestimates come out in key order: numbers in sequence (1, 2, 10, not 1, 10, 2) and factors in level order, where they were sorted as text. Domains with no sampled row are still left out, assurvey::svyby()leaves them out.An sf data frame can be passed as
datatodesign_stratified()anddesign_spread(), and an sf sample tobyinht_total()andht_mean()and tosample_summary()of a stratified or cluster sample. All of these stopped inside base R on the geometry column. Abyestimate of an sf sample is a plain data frame without the geometry.When a multistage sample with one row per cluster falls back to the jackknife and more than a fifth of the clusters were selected, the note gives the factor by which the jackknife inflates the variance between clusters. When every cluster was selected, it says that variance is zero by design and points to
design_stratified().variance = "jackknife"on a multistage sample withoutsizegives the same factor, and when every cluster was selected says thatvariance = "analytic"measures the variation within clusters only.A
bydomain gets a variance when a stratum or interval with one sampled row holds none of its units, read from thebycolumns of the frame stored with the sample. A domain of strata or intervals taken whole is exact, with a zero-width interval even at 0 degrees of freedom. Such domains were refused with a note saying the standard error would be understated, which was false for them. A domain with units in the lonely stratum is still refused, and when the frame has nobycolumns the note says the frame cannot tell. A frame row whosebyvalue is missing may belong to any domain, so a lonely stratum holding one is refused for every domain, with the same note.ht_mean()decides whetheryis a proportion, and so whether its interval is formed on the logit scale, from whatyis rather than from the values the sample drew: a logicaly, or a column of the frame whose values are all 0 or 1. A count that came out 0 or 1 in every sampled row got a logit interval, which cannot pass 1 and so never covered a mean of 1 or more; it now gets the symmetric interval. A 0/1 column added to the sample after the draw, or a numeric vector, has no frame column to read and is still taken for a proportion when every sampled value is 0 or 1, as before, now with a note saying so and thatproportion = FALSEgives the symmetric interval of a count.byestimates follow the same rule.A proportion estimated at exactly 0 or 1, such as no deviations in 60 sampled invoices, gets Korn and Graubard’s beta interval, with the sampled rows below certainty as its effective sample size, and a note saying so. It got a zero-width interval of 0 to 0. For 0 in 60 from a simple random sample the 95% upper bound is now 4.87%. A design that leaves 0 degrees of freedom, such as a Poisson sample of one row, gets the Clopper-Pearson interval over the sampled rows. A census, or a domain of rows taken with certainty, is still exact. A domain’s effective sample size for the beta interval is capped at its rows below certainty, so its interval is never narrower than Clopper-Pearson’s over them.
Estimates from
ht_total()andht_mean()holdunreachable, the number of frame rows with inclusion probability 0, and print it on a line of its own when there are any, whether or not there is a standard error.bytables carry it as an attribute and print it too.draw()warns about such rows, but a sample saved and read back, or drawn with the warning muffled, gave a total over part of the frame with no sign of the rest.The printout of
ht_total()andht_mean()shows the note whenever the standard error is 0, such as the one saying every sampled row was taken with certainty.sample_summary()gainsN_reachable, the rows the design gives a probability above 0, and prints the sampling fraction over them.Nis still every row of the frame.A stratified design whose
min_per_stratumraises a stratum, or a multistage design whosemin_per_clusterraises a cluster, can allocate different counts than drawn 0.2.0 did, as above, and a seed then selects different rows. Designs where no floor binds allocate and draw as before.design_temporal(tz = NULL), the default, lays out the window in the zone of aPOSIXcttimecolumn, and in UTC only when the column has none: aDateor string column, or aPOSIXctwhosetzoneis empty. It always used UTC, so a window of local dates over New York data ran from 19:00 to 19:00 local time. Givetz = "UTC"for the old layout. A printed design showstzas “from the time column, else UTC” when it is not set. This and the calendar fixes above change the intervals of some designs. A sample drawn earlier whose probabilities they change is refused byht_total(),ht_mean(),as_svydesign()andsample_summary(), which say the design now gives different probabilities; draw it again.design_temporal()reads timestamps and bounds written as"2024-03-01 14:30"or"2024-03-01 14", with a space or aTbefore the time. They were unparseable, so such rows stopped the draw or, underna_rm = TRUE, were dropped. A date written day or month first, such as"01/02/2024", is still refused rather than guessed.design_reservoir()returns the items of a connection or generator in the order they arrived, as it returns the rows of a data frame in frame order. They came back in the order of the reservoir’s slots. The items drawn for a seed are unchanged. A list is now sampled as a data frame is, so it gives a different sample for a seed than it did.?design_reservoirsays that the streaming path and the data-frame path use different algorithms and so give different samples for one seed.design_bootstrap(method = "block")with the defaultblock_lengthusesfloor(nrow(data)^(1/3))when the row count is a perfect cube too. The cube root in floating point fell below the whole number, so 64 rows got runs of 3 instead of 4, and 1,000 rows runs of 9 instead of 10. Such frames get different replicates for a seed.draw()with a finitedesign_reservoir(max_items =)pushes the line it reads past the cap back onto an open connection in text mode, so the next read starts with it. It was read and dropped.The default title of
plot()names theorder_byof a systematic design, itsn_startswhen above 1, and thewithinof a stratified design.deff()is a generic, with methods for the results ofht_total()andht_mean(), and passes any other object tosurvey::deff(). Its argument isobject, as insurvey’s, where it wasx, sodeff(x = r)must becomedeff(r). Attached aftersurvey, drawn’sdeff()maskedsurvey’s and refused everysurveyobject, such as the result ofsurvey::svymean(deff = TRUE). Either package’sdeff()now answers for both, whichever is attached last.bytables gain avariancecolumn, and theirnis an integer where it was a double. The printout leavesvarianceout, since it is the square ofse.The intervals of
design_temporal()are named by their start, such as2024-01-03 00:00, in the notes ofht_total()andht_mean(), the strataas_svydesign()hands tosurveyand the table ofsample_summary(). They were numbered, and a note listed them sorted as text:1,10,2.A printed estimate names its variance method as
methodholds it, the name themethodcolumn of abytable shows, and says when it is an approximation: “successive difference, an approximation” where it said “successive-difference approximation”. The README’s table of designs uses the same names.A printed
plan_size()shows a margin of1e5as100,000, where it showed1e+05. A margin that would take many digits, such as1e-300, stays in scientific notation.sample_summary()lists every stratum of the frame, one allocated no rows with 0 drawn, where it listed only the strata drawn. It gives a certainty design the groups of itsrest, after a(certain)row for the rows above the threshold, where it gave none, and groups a temporal sample by interval. The rates print with three decimals, where their widths varied.plan_size()plans two rows at least when the frame has two, since one row gives no standard error or interval, and its printout says so. The result’s newraisedisTRUEwhen this applies. A margin of two standard deviations planned one row.plan_size()no longer setscappedandshorttogether.cappedmeans that only a census meets the margin, andshortthat a smaller sample would if everyone responded.cappedwas documented as a frame that could not reach the margin however it was sampled, though a census always reaches it, and the printout now says the same.A printed proportion plan shows the
pit assumes, where it showedsqrt(p * (1 - p))assd, and the result holdsp, which isNAfor a mean or a total.plot(type = "probability")puts frame rows on its axis and centres a plateau on each row, so the first and last rows are as wide as the others and a one-row frame is drawn. The last row had no width, so a take-all unit at the end of a frame sorted by size did not show, and frames of two to four rows had repeated tick labels. The mean’s label sits inside the panel.plot(type = "selection")andplot(type = "map")of a design that samples with replacement count draws and distinct rows, as in “60 draws, 51 distinct rows of 240”, and ring each row drawn more than once.plot()of adesign_bootstrap()shows its first replicate and says so, whatever itsoutput. It marked every row drawn in any replicate, which at the default 1,000 replicates is every row.plot(type = "probability")no longer points a bootstrap to the selection view.plot()passesxlim,ylim,aspand the other graphical parameters in...to the panel in place of its own settings. Each one the plot also set stopped with “formal argument matched by multiple actual arguments”, so a map could not be givenasp = 1and the probability view could not be zoomed. Intype = "probability"the rules, the axis and the mean line follow the limits given.plot(type = "map")of adesign_spatial(), or of adesign_spread()withscale = FALSE, draws both axes to the same scale, so the map shows the distances the design works with. Longitude and latitude are drawn with a degree of longitude atcos()of the middle latitude. Other columns fill the panel as before, andasp = NAgives that back for these two designs.plot(type = "map")says under its title which columns ofacrossit leaves out when there are more than two, and how many selected rows it could not place because a coordinate is missing. It used the first two columns without saying so and counted rows it did not draw among those selected. When it thins the background it keeps at mostmax_dotsof the unselected rows and says “background thinned to 50 of 210”. Its note “50 of 240 rows shown” came with 71 rows drawn.The default title of
plot(), and the description of a design in messages, gives every argument that changes what the design draws when it differs from the default:replace,start,allocation_by,cost,min_per_stratum,min_per_cluster,max_items,block_length,output,batches,scaleandna_rm, thecoordsofdesign_spatial(), theabove,thresholdandrestofdesign_certainty(), and theunitofdesign_temporal(). Several column names are wrapped inc(), so the title reads as R code.design_simple(n = 10)anddesign_simple(n = 10, replace = TRUE)had the same title, as did a reservoir with and withoutmax_items, and a certainty design’s title had no arguments at all.balanced = FALSEis left out. A title or subtitle too long for the figure is drawn smaller, down to two thirds of its size, and past that is cut and ends in “…”, where it ran off the edge of the figure.A printed design shows what a default left as
NULLmeans:startisrandomfordesign_systematic(), andnisnrow(data)and the defaultblock_lengthisnrow(data)^(1/3), rounded downfordesign_bootstrap().A
seedis applied with R’s default generator,set.seed(seed, kind = "Mersenne-Twister", normal.kind = "Inversion", sample.kind = "Rejection"), whatever generator the session has selected, and the session’s generator is restored with its state. A seed drew another sample afterRNGkind("L'Ecuyer-CMRG")or undersample.kind = "Rounding". A session left at R’s defaults draws the same samples as before. This holds for theseedofdraw(),inclusion_prob(),joint_prob()andplot().draw()keeps the row names of a frame that has its own, such as the car names ofmtcars, on the rows drawn, made unique bymake.unique()where a row is drawn more than once. They were replaced by 1, 2, and so on. Automatic row names are still numbered afresh, and a tibble has none.inclusion_prob(simulate = TRUE)andjoint_prob(simulate = TRUE)give a warning that the draws raise once, at the end, with the number of draws that raised it.max_itemsbelow the rows of a frame and a systematic start past the last row warned once per draw, hundreds of times, and an empty stratum or cluster was not reported. These two warnings have the classesdrawn_stream_truncatedanddrawn_empty_start, and a random systematic start past the last row is called random, where the message namedstart. A warning whose details change from draw to draw, such as the empty cluster or the random start it names, is shown as the first draw gave it, with the number of draws that gave one like it. When each draw gives the same few warnings of one kind, the message says how many each draw gave.inclusion_prob(simulate = TRUE)andjoint_prob(simulate = TRUE)time the draws after the first two, which carry one-off costs such as loading a package, and a run projected to take more than 30 seconds says how long, with a progress bar in an interactive session. A run of hours, such as the defaultRfordesign_spread()on 10,000 rows, gave no sign of progress.The note of a successive-difference variance says that systematic sampling has no design-unbiased variance estimator only when the walk has a step of 2 rows or more.
design_systematic(n =)withnabove half the rows walked, anddesign_stratified(within = design_systematic())with every stratum taking more than half its rows, have a step under 2 rows, at which every pair of rows can be drawn together. The variance is the same successive-difference approximation.
New
ht_total()andht_mean()takealternative = "less"for a one-sided upper bound and"greater"for a lower bound, labelled as such when printed. The open end ofciis-InforInf, or 0 or 1 for a proportion. A one-sided bound is the end of a two-sided interval at1 - 2 * (1 - level), which is how it had to be asked for before.ht_mean()takesproportion, to say whetheryis a proportion rather than leave it to the rule above, andci_method = "beta"for Korn and Graubard’s interval, the onesurvey::svyciprop(method = "beta")gives, with its effective sample size capped at the number of sampled rows below certainty.ht_total()andht_mean()takecontrast, weights over thebydomains such asc(a = 1, b = -1), and return the weighted sum of the domain estimates with its standard error, interval and degrees of freedom, as adrawn_contrast. The variance comes from one run of the design’s estimator, so the covariance between domains is counted, and for simple random, stratified, cluster and multistage samples the standard error equals that ofsurvey::svycontrast()onsurvey::svyby(covmat = TRUE). A difference of domain means needed linearised residuals built by hand, and thesurveyroute stopped with an error for systematic PPS samples. The interval is symmetric, for proportions too.certainty_set()gives the rows of the frame thatdesign_weighted()withmethod = "systematic"or"poisson", ordesign_spread()withsize, takes with certainty, before anything is drawn. Itsthresholdattribute, the smallest size among them, can be passed todesign_certainty()to take the same rows with the cut-off made explicit.design_stratified()takes the number of rows to draw from each stratum asallocation: a named vector such asc(north = 10, south = 5, east = 5), or for severalstratacolumns a data frame of those columns andn.ncan be left out and is their sum. A stratum of the frame with no count, a count for a stratum the frame does not have and, without replacement, a count above the rows in its stratum are refused by name.inclusion_prob(),joint_prob(), the variance estimators,as_svydesign()andsample_summary()follow the counts as given.design_stratified(allocation = "neyman")takes the standard deviation of each stratum asallocation_by, from a pilot or an earlier survey, in place of a frame column: a named vector, or a data frame of thestratacolumns andsd. The frame then needs no such column fordraw(),inclusion_prob(),joint_prob()or the variance estimators. The newcostargument takes the cost of one row in each stratum in the same forms and splitsnin proportion tosize * sd / sqrt(cost), the split of least variance for its total cost (Cochran 1977, section 5.5). Before, the only way to get either was a made-up frame column with the wanted spread. A stratum of the frame missing from either is refused by name, and a value for a stratum the frame does not have is ignored, so the same values serve therestofdesign_certainty()when every row of a stratum is above the threshold. A negative or infinite standard deviation, a cost of 0 or less, andcostwithout Neyman allocation are refused when the design is built.allocation_table()shows, before drawing, howdesign_stratified(), on its own or as therestofdesign_certainty(), splitsnover the strata of a frame: each stratum’s size, the rows drawn from it, their inclusion probability, the standard deviation and cost a Neyman split used, and whether the stratum was held at its floor, capped at its size, taken whole or left with no rows. It comes from the same computation asdraw()andinclusion_prob().design_spatial(coords =)anddesign_spread(across =)take the name of a POINT geometry column, such as the geometry of ansfframe, and read each row’s position withsf::st_coordinates(). A geometry column with a CRS of its own is used in that CRS.plot(type = "map")places rows by it too.design_spread(across =)takes Date and date-time columns, counted in days and in seconds, so a sample can be spread over time and space together.plot(type = "map")gives them date axes. Any other column that is not numeric is refused with a pointer toas.numeric().design_spread()takesstrata, to spread a sample within each stratum, andallocation, to splitnover them by"proportional"or"equal"allocation or by a count for each stratum, asdesign_stratified()does. Each stratum is scaled, sized and spread on its own.ht_total()andht_mean()add up the strata’s local mean variances, count degrees of freedom as for a stratified sample, and refuse by name a stratum with one sampled row below certainty.as_svydesign()hands the strata tosurvey, andallocation_table()andsample_summary()list them with the rows each keeps oncena_rmdrops those with a missing value. A count for a stratum thatna_rmempties is refused with that reason. The help page advised spreading within strata for large frames without a way to do it, and samples drawn stratum by stratum and bound withrbind()are refused by the estimators.design_bootstrap()takesmethod = "circular", the circular block bootstrap of Politis and Romano (1992), in which a run of rows can wrap from the last row to the first, so every row appears equally often on average. Undermethod = "block"the first row and the last appear only1 / block_lengthas often as a row in the middle, which?design_bootstrapnow says.design_bootstrap()takesoutput."indices"returns the replicates as an integer matrix of row numbers with a column per replicate, and"weights"as a matrix of the number of times each replicate drew each row, whichsurvey::svrepdesign(type = "bootstrap", combined.weights = TRUE)takes as replicate weights. Neither copies the data. The default,"rows", still returns the stacked frame, and for one seed all three hold the same replicates.design_reservoir()takesbatches. Withbatches = TRUE, a function that returns a data frame on each call is sampled by row rather than by data frame: Algorithm L runs over the rows,draw()returnsnof them as one data frame, andmax_itemscounts rows. A seed gives the same rows however the stream is cut into batches.design_systematic()takesn, in place ofinterval, for a sample of exactlynrows. The step is the number of rows walked divided bynand need not be whole: a startuis drawn from (0, 1), each row coversn / Nof a line from 0 ton, and the rows underu,u + 1, …,u + n - 1are taken. Every row has probabilityn / N,joint_prob()gives each pair the exact share of starts that take both, and the successive-difference variance has no term for a random size. Before, anintervalthat did not divide the frame gave one of two sample sizes, and a fractionalintervalwas refused, so 30 rows from 100 could not be asked for.intervalkeeps its place as the first argument, and a seed draws the same rows with it as before. A design saved by drawn 0.2.0 and read back withreadRDS()gets the fields added since, so it draws and gives the probabilities it did then.design_systematic()takesn_starts, for a replicated systematic sample. Withn_starts = m,mdifferent starts are drawn from1:(m * interval)and each is walked at a step ofm * interval, so every row keeps probability1 / intervaland the expected sample size is unchanged.joint_prob()gives the exact joint probabilities, andht_total()andht_mean()use the variance between the replicates’ totals,(1 - 1 / interval) * var(t_r) / m, which is design-unbiased, onm - 1degrees of freedom.as_svydesign()hands the replicates tosurveyas clusters and gets the same standard error. One start has no unbiased variance at all, and the successive-difference approximation was the only figure on offer.design_stratified()takeswithin = design_systematic(order_by = "x")for systematic sampling within strata. The strata are allocated as before, and each is sorted onxand walked from a start of its own at a step ofN_h / n_hrows, so every row keeps probabilityn_h / N_h.joint_prob()gives the exact joint probabilities,ht_total()andht_mean()add up the strata’s successive-difference variances on the degrees of freedom of a stratified sample, andas_svydesign()handssurveythe strata. Other designs aswithinare refused, and so isdesign_systematic()withintervalornthere, since the allocation sets each stratum’s size.design_systematic()with neither is now built for this role, and refused if drawn on its own.design_weighted()takesstrataandallocation, for sampling in proportion to size within strata.nis split over the strata by"proportional"or"equal"allocation over their rows, or by a count for each stratum, asdesign_stratified()splits it, and each stratum is then sampled by"systematic"or"poisson"on its own, with rows past certainty taken with certainty within it."successive"is refused withstrata.inclusion_prob()givesn_h * p_iwithin each stratum,ht_total()andht_mean()add up Deville’s approximation over the strata for"systematic"and count degrees of freedom as for a stratified sample, a stratum with one sampled row below certainty is refused by name, and the jackknife deletes within strata.as_svydesign()handssurveythe strata, with Brewer’s approximation within each, andallocation_table()andsample_summary()list them with the rows each keeps oncena_rmdrops those with a missing weight. A count for a stratum thatna_rmempties is refused with that reason. Samples drawn stratum by stratum and bound withrbind()were the only way before, and the estimators refuse them.design_multistage()takessize, a column holding each cluster’s size measure, to select clusters with probability proportional to it by systematic PPS, taking a cluster with certainty wheren_clusterstimes its share passes 1, and then the samen / n_clustersrows from each by simple random sampling. A row’s inclusion probability is its cluster’s stage-one probability timesm / N_i, so a measure equal to the cluster’s row count gives every rown / N.ht_total()andht_mean()use Deville’s approximation over the estimated totals of the clusters below certainty plus the variance within the selected clusters, which is the exact two-stage estimator when every cluster has the same chance, and count each cluster taken with certainty as a stratum of its rows.as_svydesign()handssurveythe two stages with Brewer’s approximation at the first, or one stage of clusters when a selected cluster gives one row of several. A measure that differs within a cluster,allocation = "proportional"and annthatn_clustersdoes not divide are refused.inclusion_prob()givesdesign_cluster(balanced = TRUE)its exact inclusion probabilities, where it refused them as having no closed form, soplot(type = "probability")andsampling_weight()work for it too. A row of a cluster ofN_irows has(a / A) * E(m) / N_i, the takemaveraged over the selections that include its cluster, worked out from the sorted cluster sizes. The help page quoted simulated values of 0.41 and 0.34 for clusters of 4 and 6 rows where the exact ones are 0.417 and 0.333.draw(weights = TRUE)weightsdesign_cluster(balanced = TRUE), anddesign_multistage()withoutsizeunder proportional allocation, with annthatn_clustersdoes not divide or with a cluster smaller than the take, conditional on the clusters it selected, all of which it refused before..probis(a / A) * m_i / N_ifor them_irows taken from clusteri, and the sample records the clusters selected. The total is unbiased given the selection, and so over every selection.ht_total()andht_mean()estimate its variance with the two-stage formula at each cluster’s own take, ona - 1degrees of freedom;as_svydesign()hands it tosurveyin two stages, with the same standard errors; andsample_summary()says the weights are conditional. Proportional allocation needsmin_per_clusterof at least 1 for this.inclusion_prob()still refuses the multistage cases, whose exact probabilities average the chance given the clusters selected over every possible selection.replicate_weights()builds replicate weights from a sample forsurvey::svrepdesign(), with thetype,scaleandrscalesto pass with them. For most designs they are the jackknife ofht_total(variance = "jackknife"), deleting units within strata with each stratum’s finite population correction and holding units taken with certainty fixed; where the default ofht_total()is another estimator, such as Deville’s approximation for systematic PPS, they give the jackknife’s standard error, not the default’s. A systematic sample, alone or within strata, gets successive-difference replicates in walk order, without the pair the circular form adds between the two ends of the walk, and a replicated one gets a replicate per start; both give the standard errorht_total()gives by default.survey::as.svrepdesign()stops on the probability-proportional-to-size and Poisson designsas_svydesign()hands over, which is a limitation ofsurveythat?as_svydesignnow states, for a systematic sample builds a jackknife that ignores the walk, and for balanced clusters anddesign_multistage()withoutsizekeeps a first-stage correction the jackknife ofht_total()leaves out. Poisson sampling, which the jackknife understates, is refused, and so are replicate weights that would take more than about 1 GB.frame_totals()gives the population totalssurvey::calibrate()takes, the column totals ofmodel.matrix(formula)over the rows of the stored frame that the design could reach, or withtable = TRUEthe countssurvey::postStratify()andsurvey::rake()take. Rows outside a region or time window, past a reservoir’smax_itemsor dropped byna_rmare left out, and a missing value in the rows counted is refused. A name informulathat is not a column of the frame, such ascutoffin~ I(w > cutoff), is read from where the formula was written; a term with no frame column in it, such as~ cutoff, has no value per row and is refused. Calibrating a design fromas_svydesign()needed the totals built by hand. The estimation article has an example; calibration itself stays withsurvey.The results of
ht_total()andht_mean(),bytables and contrasts havecoef(),vcov(),confint()andas.data.frame()methods, andtidy()methods forgenerics::tidy()and sobroom::tidy(); generics joinsSuggests.confint()gives the interval the estimate holds, on the design’s degrees of freedom and, for a proportion, on the logit or beta scale, and forms it again at anotherlevel.survey::SE()andsurvey::cv()work through these.vcov()of abytable givesNAfor the covariances between domains, which are not estimated, and 0 for two domains of a stratified sample that share no stratum. Results recordvariable, the name ofy, so estimates of several variables can be bound withrbind()of theiras.data.frame(), andn_random, the sampled rows below certainty.?ht_totaldescribes them under “Working with the result”.sample_summary()reportsn_kish, Kish’s effective sample sizesum(w)^2 / sum(w^2);n_certain, the sampled rows taken with certainty, withcertain_bysplitting them into those above adesign_certainty()threshold, those a size measure put at probability 1 and those in a group the design takes whole, whichever rows a Poisson draw happened to hold; andexpected_n, the sum of the inclusion probabilities, printed besidenwhen the sample size is random, as under Poisson sampling.plot(type = "map")of adesign_spatial()design draws the outline ofregion, with each edge of a longitude/latitude region along its great circle under spherical geometry, which is how the design decides which rows are inside.as_drawn()rebuilds a weighted sample from rows read back from a CSV file, a spreadsheet or a database table, which keep the rows and lose the design. It matches each row to the frame through.row, or through id columns named inby, and works out the inclusion probabilities again from the design. Ids that are missing, repeated or not in the frame, a frame reordered since the draw, which shows in the columns the rows share with it, and a sample short of the rows drawn, such as the rows that responded, part of a cluster or a row taken with certainty, are refused. Text such as"F"or"f"read back asFALSE, a date-time read back in UTC and an infinite value are not taken for a reordered frame.add_fieldwork()joins fieldwork results keyed by an id to a sample, in the sample’s own order and keeping its design, and refuses repeated or unknown ids and columns the sample already has; a sampled row with no result gets a missing value. A sample that had been through a file could not be estimated from, andmerge()dropped the design. The refusal of a sample without its design names both.compact_sample()replaces the copy of the frame a weighted sample holds with the columns its design reads, plus any named inkeep. Each sample holds its own copy of the whole frame, in memory and in every file it is saved to, which hands the frame, with any personal data in it, to whoever receives the file. A simple random sample of 100 from a three-column frame of a million rows saved to 28 MB, and to 8 MB compacted, most of it the frame’s inclusion probabilities. Estimates,as_svydesign()andsample_summary()are unchanged;ht_mean(estimator = "ht")withby,frame_totals(), and the standard error of a domain when a stratum has one sampled row, need their columns inkeep, and say so.?drawdescribes the cost.ht_mean()takesna_rm. Withna_rm = TRUEit estimates the mean over the sampled rows withypresent, as a domain of the whole sample, with the design’s own variance estimator, and equalssurvey::svymean(na.rm = TRUE)onas_svydesign(), by domain too. The printed result says how many rows were left out and that they are assumed missing completely at random, and names anybydomain left without a row because every sampled row of it hasymissing.?ht_totalhas a section on missing values and nonresponse, with the weighting-class adjustment to use when that assumption fails, and the estimation article shows the steps.design_simple()anddesign_spread()takereserve, a number of units to list after the main sample for replacing units that fieldwork finds cannot be reached.draw()returns the main sample and then the reserves, numbered in the order they are used by a new.reservecolumn; the main sample is the one the design draws withoutreserve. Fordesign_simple()the list is one random draw, and fordesign_spread()the reserves are a second spread sample from the rows the main sample left, so they cover the space evenly too.design_spread()takesreserveonly withoutsizeandstrata, both refusereservewithn = 0, anddesign_certainty()refuses arestwithreserve. A printed simple or spread design shows areserveline.ht_total(),ht_mean(),as_svydesign()andsample_summary()refuse the list. The newuse_reserves()takes it with the units found unavailable, replaces them with the first available reserves, and returns a sample weighted atn / (N - u)over the frame without theuunits found unavailable. Its estimates describe the units that can be reached, and?use_reservessays what that assumes. Every unit nobody visited is taken as available, which the printedunreachableline of an estimate says; the estimate keepsuinunavailable.as_drawn()rebuilds a list read back from a file through its.reservecolumn.ht_ratio()estimates the ratio of two population totals,sum(y / pi) / sum(x / pi), such as audited value per unit of book value, with a standard error from the linearised residuals(y - R x) / X_hatand the design’s own variance estimator, on the design’s degrees of freedom. Withbyit gives each domain’s ratio, estimated from the whole sample. For the designsas_svydesign()maps with identical standard errors it equalssurvey::svyratio(), andsurvey::svyby(..., survey::svyratio)by domain; systematic, spread and systematic PPS samples get the estimatorsht_total()uses for them. A ratio needed linearised residuals built by hand, or the hand-off tosurvey. Its result has thecoef(),vcov(),confint(),as.data.frame(),tidy()anddeff()methods of the other estimates.ht_total()takesratio, the name of a frame columnx, and returns the ratio estimator of the total: the ratio ofytoxin the sample times the total ofxover the frame rows the design can reach, read from the frame stored with the sample. It equalspredict(survey::svyratio(), total =), and whenyis close to proportional toxit is more precise than the Horvitz-Thompson total. A missingxin a frame row the design can reach is refused, and so isratiowithby.ht_total()andht_mean()take several column names asy, and return one table with a row per variable, or per variable and domain withby, each row what a call for that variable alone gives. Itsvcov()holds the covariances between the variables’ estimates, each from one more run of the design’s estimator,(V(z_a + z_b) - V(z_a) - V(z_b)) / 2, which equalsvcov(survey::svytotal(~a + b))for the designsas_svydesign()maps with identical standard errors.ht_total(s, c("y", "w"))stopped with a message thatymust be a numeric column name, and the covariance of two estimates, which the standard error of their difference needs, was not available at all. Aythat is none of one column name, several column names, or a numeric vector or factor as long as the sample is refused with a message that lists those forms and says whatywas, and a column that is not numeric is named with its type.ht_quantile()estimates medians, quartiles and other quantiles, overall or by domain, from the Hajek estimate of the distribution function. The estimate atpis the smallest sampled value whose estimated distribution function ispor more,survey::svyquantile()’s default rule. Its interval is Woodruff’s: the interval for the distribution function at the estimate, from the design’s own variance estimator, is carried back to the scale ofy, and the standard error is that interval’s width over2 t. For the designsas_svydesign()maps with identical standard errors it equalssurvey::svyquantile(interval.type = "mean")except in three places, and systematic, spread and systematic PPS samples get the estimatorsht_total()uses for them. For apbelow the share of the weight held by the smallest sampled value,survey’s rule takes the second smallest value as the estimate andht_quantile()the smallest. Apwithin1e-9above a share of the weight, such asseq(0, 1, 0.01)[71], gives the value at that share, wheresurveyandstats::quantile(type = 1)give the next. A quantile at the largest sampled value, where that variance is 0 whateverydoes, gets no standard error, with a note, wheresurveygives an interval of no width. Quantiles were available only throughas_svydesign(). A logicalyis refused with a pointer toht_mean(). The result hascoef(),vcov(),confint(),as.data.frame()andtidy()methods, andconfint()at another level forms the Woodruff interval again.vcov()of several quantiles hasNAfor their covariances, which are not estimated.ht_total()andht_mean()take a factor or character column asy, or a factor as long as the sample, and return the estimated count or share of each level as a table led by alevelcolumn, with a proportion’s interval for each share and the covariances between levels invcov(), assurvey::svytotal(~f)andsurvey::svymean(~f)give them. Such aywas refused, and shares took one call per level with an indicator such ass$f == "a", which?ht_meannow shows.ht_total(),ht_mean()andht_ratio()take a single number asyorxand use it for every row, soht_total(s, 1)estimates the number of frame rows the design can reach, and withbythe number in each domain. A single number was refused.plan_size()takes the result ofht_mean()orht_total()on a pilot asdeffand uses its design effect. It refuses a mean whentarget = "total"and a total for a mean or a proportion, since the two design effects differ for one sample, by a factor of 42 in one cluster sample.plan_size()takesstrata, a data frame with a row per stratum holding its sizeNand the standard deviationsdwithin it, or the expected proportionp, and plans a stratified sample: the smallestnwhose split byallocation("proportional","equal"or"neyman", with an optionalcostcolumn for Neyman) meets the margin, with at leastmin_per_stratumrows from each stratum, 2 by default. Amin_per_stratumof 0 is refused, since without a floor a small stratum gets no rows untilnis large, and the estimate leaves it out.nis split asdesign_stratified()splits it, rounding included, and the split is returned asallocation, whichdesign_stratified(allocation =)draws as given. Stratification could enter a plan only throughdeffbefore.deff_cluster()gives the design effect1 + (m - 1) * iccof takingmrows from each cluster when rows of one cluster correlate aticc, to pass toplan_size(deff =)before a pilot has measured one.A plan from
plan_size()can be passed asnto every design that takesn, such asdesign_simple(n = plan), where it was refused before.plan_size()takes several values ofmargin,sd,p,deffandresponse, one per plan, and returns a data frame with a row per plan, andas.data.frame()turns a single plan into such a row.plot()takessub, a string added to the end of the line under the title. Asubgiven before was matched to an internal argument of the same name, andtype = "map"stopped with ‘graphical parameter “bg” has the wrong length’.A sample from
draw(weights = TRUE)records how it was drawn in the attributedrawn_meta: the seed, the generator, the version of drawn, the time and the number of frame rows.sample_summary()returns it asdrawnand prints the seed, the version and the date. A sample fromas_drawn()records that it was rebuilt, anduse_reserves()keeps the record of the draw.
Speed and memory
- Stratum and
bykeys are built from each column’s integer codes, so their cost grows with the number of rows, however many combinations the columns’ levels could form. On 200,000 rows keyed by two columns of 3,000 values each, the key took 8 seconds where it now takes 0.2, and at 6,000 values each it ran out of memory. -
inclusion_prob(),joint_prob()anddraw(weights = TRUE)take time linear in the number of strata of a stratified design. At 40,000 strata each took about 9 seconds.inclusion_prob()andjoint_prob()now take under a tenth of a second, anddraw(weights = TRUE)half a second. -
design_cluster()anddesign_multistage()find the rows of the selected clusters in one pass over the frame instead of one pass per cluster. Selecting 1,000 clusters from a million rows took 16 seconds and now takes 0.2. The clusters chosen for a seed are unchanged. - The jackknife sums each unit with
rowsum(), so its time grows with the number of rows rather than with rows times units. 20,000 rows took 2.6 seconds and now take 0.03. - The analytic variance of simple random, reservoir, spatial, stratified, temporal and equal-take multistage samples, alone or as the
restofdesign_certainty(), is computed from the variance within each stratum, interval or cluster, and for a multistage sample the variance between the estimated cluster totals, in time and memory that grow with the number of sampled rows. The Sen-Yates-Grundy sum over every pair of sampled rows, which gives the same figures, held several matrices with a row and a column per sampled row: a stratified sample of 4,000 rows took 4.8 seconds and 1.4 GB, growing with the square of the sample, and everybydomain built them again. The same sample now takes 0.01 seconds, and 10,000 rows take 0.04. A census of one row gets its variance of 0 this way rather than from the jackknife. -
joint_prob()refuses a matrix that would need more than about 1 GB, from about 11,200 rows, and gives the size androws = s$.rowas the way to ask for the rows of a samples. It used to go on and could exhaust memory. The full matrix is still the default. Stratified, temporal, cluster, multistage and systematic joint probabilities are filled one group at a time and need little memory beyond the matrix itself, where they needed 4 to 12 times its size: a stratified matrix over 5,000 rows took 2.4 GB and 6.7 seconds, and now takes 0.2 GB and 0.4 seconds. -
byestimates work out the strata, clusters, systematic order, certainty split, spread neighbours and joint probabilities once per call rather than once per domain, and the analytic variances of simple random, reservoir, spatial, stratified and temporal samples, alone or as therestofdesign_certainty(), come from one pass over all the domains. 200 domains of a stratified sample of 1,000 from 100,000 rows took about 50 seconds and now take 0.1; 200 domains of a spread sample of 1,000 from 20,000 rows took 16 seconds and now take 0.3.variance = "jackknife"places the frame’s rows in its strata once per call too: 200 domains of a stratified sample of 300 from a million rows took 21 seconds and now take 1.2. The standard errors agree with the old ones to rounding error. -
inclusion_prob(),draw(weights = TRUE)and the estimators of adesign_temporal()sample count the rows of every interval in one pass, where they went over the rows once per interval. 200,000 rows in hourly intervals over a year took about 6 seconds and now take 0.03. -
design_bootstrap()subsets the data once for all replicates, where it subset it once per replicate and bound the pieces withrbind(). The default 1,000 replicates of a 5,000-row frame with four columns took 13 seconds and now take 0.4, with the same rows for a seed. It warns, with classdrawn_bootstrap_size, when the stacked frame would pass 10 million rows, and points tooutput. -
design_reservoir()on a connection or generator grows its reservoir as the stream fills it. It set aside allnslots before reading, son = 5e7took 400 MB for a stream of five items. It counts the items read in a double, so a stream of more than 2,147,483,647 items no longer stops with “missing value where TRUE/FALSE needed”. -
design_reservoir()reads a connection 10,000 lines at a time and works out Algorithm L’s swaps within each block, where it calledreadLines()once per line. Drawingn = 100from 500,000 lines took 1.2 seconds and now takes 0.1, with the same sample for a seed. A largerngains less, because it makes more swaps and each costs what it did;n = 20000went from 2.0 seconds to 0.8.
Handing off to survey
-
as_svydesign()handssurveya copy of the sample, so an in-place sort of the sample afterwards no longer changes the survey design’s standard errors. - Units taken with certainty go to
surveyas one primary sampling unit per stratum with anfpcof 1, through a new.psuid column, sosurvey::degf()gives the same degrees of freedom asht_total()for certainty designs, strata and intervals taken whole, PPS samples with certain units, and the clustersdesign_multistage()anddesign_cluster(balanced = TRUE)take whole when they select every cluster, andsurvey::svyciprop()gives the same interval asht_mean().surveyhad counted each certain row as a unit, and each cluster taken whole as one more. - A census, a sample whose every
.probis 1, goes tosurveyasids = ~1withfpcthe number of rows. Under systematic PPS, alone or as a certainty design’srest, Poisson sampling anddesign_spread(size =)it stoppedsvydesign()with “subscript out of bounds”. An empty sample is refused with a message instead of failing insidesurvey, and so is a certainty sample whoserestdrew none of the rows below the threshold, whichsurveywould have reported as exact. -
?as_svydesign, the estimation article andcran-comments.mdno longer say thatsurveyagrees with systematic PPS within 0.2%. In simulations on frames of 100 to 300 rows with gamma and lognormal sizes, standard errors of totals agreed within 0.5% in most samples and within 3% in all; those of means differed more as the sampling fraction grew, typically by 3 to 7% at one half and by up to 12%. Where the probabilities below certainty spread from 0.05 to 0.95, totals differed by up to 9% and means by up to 17%. -
as_svydesign()labels strata built from several columns asa . b. The labels held a carriage return, which broke a CSV export of the design variables. Where two labels would read alike, the strata are numbered instead, sosurveycannot merge them. -
as_svydesign()numbers the clusters in.cluster.surveymade a factor of the labels, which merged two that print alike, such as0.3and0.1 + 0.2, into one primary sampling unit. The cluster column’s name went into theidsformula as it stood, so a name with a space, such ascluster id, stoppedsvydesign()with a parse error, andcl-1beside a columnclwas read ascl - 1, which clustered oncl. -
as_svydesign()hands overdesign_certainty()over a cluster, multistage, Poisson or replicated systematicrest, which it refused as having no singlesurveydesign. The certainty rows go tosurveyas one more primary sampling unit beside the clusters or replicates, taken whole at both stages of a two-stagerest, and a Poissonrestbecomessurvey::poisson_sampling()built from the whole sample’s.prob, with the certainty rows at probability 1. Totals, standard errors, domain estimates and degrees of freedom agree withht_total()as they do forreston its own. - A sample from
design_multistage(), with or withoutsize, ordesign_cluster(balanced = TRUE)with one sampled row from a selected cluster of several goes tosurveyas one stage of clusters with nofpc. That is the ultimate-cluster design behind the jackknifeht_total()falls back to, so the standard errors agree. In two stages,surveystopped with “has only one PSU at stage 2”. -
as_svydesign()refuses a sample with a column named.stratum,.cluster,.psu,.fpc,.fpc2or.unit. It wrote the design into those columns over the user’s, so an analysis of such a column insurveyread the design’s values. -
as_svydesign()refuses unnamed arguments in.... It dropped them, soas_svydesign(s, ~cl)handedsurveythe mapped design and ignored~cl. -
?as_svydesignandcran-comments.mdsaidsurvey’s standard error is larger thanht_total()’s fordesign_spread(). It is larger whenyvaries smoothly over the coordinates, and smaller in most samples whenyhas no spatial pattern or the sampling fraction is large, because the local mean approximation has no finite population correction.?as_svydesignalso says that the agreement it states holds undersurvey’s defaultoptions(survey.ultimate.cluster = FALSE).
Documentation and site
- References in the help pages and the articles give a DOI for every work that has one, checked against Crossref. A citation whose year began a line turned into a numbered list in the spatial sampling article and in this changelog, as did a sentence ending “passes 1.” in
?certainty_set; each reads as written now. -
?ht_totalsaid the exact multistage estimator understates by about a third with one row per cluster. It understates byf1times the within-cluster component, wheref1is the share of clusters selected, and the jackknife used in its place overstates byf1times the between-cluster component, which came to 3.3 times the true variance in one example with 30 of 40 clusters selected.?design_multistageand?inclusion_probgive the probability underreplace = TRUE. -
?designsand?design_stratifiedname all three allocation rules,"neyman"included, where they described"proportional"and"equal"only. -
?design_spreadgives the local-mean variance estimator’s ratio to the true variance by sample size and sampling fraction, from 1.0 to 4.9 in its table and 18.9 for 4 rows from 8, and saysdeff()carries the same overstatement. It said 1 to 1.6 times. A ratio slightly below 1 occurs too. -
?design_spatialexplains how the edges of a longitude/latitude region bow under spherical geometry, how to keep them on their straight lines in degrees, and how to pass a region larger than a hemisphere as a list of parts. -
?design_bootstrapand the choosing-a-design article say that resampling rows suits independent rows, and point a sample drawn with strata or clusters tosurvey::as.svrepdesign(), which resamples clusters within strata. The help page said the bootstrap was the tool for any statistic the estimators do not cover, and the article that it estimates the sampling distribution of whatever you like.?design_bootstrapalso says thatn = 0gives a frame with no rows that keeps its.replicatecolumn, and the README’s table of designs lists the circular block bootstrap. -
?design_reservoirsays that each line of a connection is an item, a CSV header included, and shows how to read the header off an open connection before drawing. It said that items pastmax_itemswere never read; one is read, to tell a longer stream from one of exactlymax_items, and a function is called once past the cap. A connection that is not open is opened, read and closed, asread.csv()does. Underbatches = TRUEonly the column names of each batch are compared, and a column whose type differs between batches takes the typerbind()gives the sampled rows. -
?design_systematic,?inclusion_proband?joint_probsay that a fixedstartmakes the design deterministic, soinclusion_prob(),sampling_weight(),joint_prob(),draw(weights = TRUE)and the estimators refuse it, whileinclusion_prob(simulate = TRUE)reports its probabilities of 0 and 1. The table in?inclusion_probgave1 / intervalfor every row without saying the start must be random.joint_prob()and the estimators now refuse a fixed start with the same message asinclusion_prob(), which says to leavestartasNULL. -
?plan_sizesays which design effect to pass: that ofht_mean()for a mean or a proportion and that ofht_total()for a total. A mean’s design effect used for a total planned a sample that met its margin in 23% of samples, against the 95% planned. It also says that a design effect from one pilot is noisy and worth rounding up, and whendeff()givesNA. -
?plan_sizesays thatmarginis the half-width the plan expects, so the interval a sample reports is wider about half the time, and gives the t quantile for 3, 4 and 6 clusters as 2.2, 1.6 and 1.3 timesz, where it said “slightly wider”. It says that the logit intervalht_mean()reports for a proportion is asymmetric, with an upper arm that exceedsmarginin most samples whenpis small, and cites chapter 4 of Cochran (1977) for both corrections. -
?drawand?designssay that aseedrestores the caller’s random number stream and thatseed = NULLdraws from and advances it.?designssaid the stream was always restored. -
?draw_designgives the contract for a design class of your own: a method takesdesignanddataand returns rows ofdata, which is enough fordraw()andsimulate = TRUEbut not forweights = TRUEor the estimators. The site lists it under “Extending”, where it was a page with no contract besidedraw(). -
?inclusion_probsays what a simulation costs:Rdraws, each of which takes time in proportion toN^2fordesign_spread(). - Claims that went further than the code or the simulations are corrected.
?ht_totalsaid the successive-difference variance of a systematic sample stayed near the truth. Its average over the starts depends on the frame, 1.6 times the true variance on the estimation article’s example; a cycle whose period divides the interval understates it as a matching period does; a period of twice the interval overstated it 29-fold in one simulation; and under a pure trend it falls towards6 / nof the truth.?ht_totalalso says that intervals cover less often thanlevelwheny / piis skewed and the sample small, 87% to 91% in most of the cases it cites, that the Hajek mean covers less often still whenyis close to proportional to size, through its ratio bias and a variance estimate that runs low, and thatvariance = "jackknife"declines for systematic and Poisson samples, where it said the jackknife always resamples.?ht_meansays the Hajek and Horvitz-Thompson means coincide for an equal-probability design that can reach every row of the frame, which a region ormax_itemscan prevent.?designssays that onlymethod = "successive"ofdesign_weighted()returns rows in draw order.?design_weightedsays that Poisson sampling takes rows past certainty with certainty and rescales the rest, as systematic PPS does, where it said they were capped at 1, and puts successive sampling of weights1:10atn = 5up to about 36% from proportional, by exact enumeration, where it said 35%.?design_systematicsays thatstartcounts along the walk, sorted byorder_bywhen given, and?drawthat a seed is sure to draw the same rows only from a frame in the same row order. The estimation article checks five designs against their exact variance at 1,000 draws, where the ratios of 0.85 and 0.87 it printed for cluster and Poisson samples were Monte Carlo error. The spatial-sampling article shows the mean it promised, and the choosing-a-design article says why one cluster sample’s design effect came out below 1. -
?drawnand the package description give Deville’s (1999) approximation as the variance for systematic probability-proportional-to-size samples, where they gave it for every probability-proportional-to-size design. Poisson samples get the exact Horvitz-Thompson variance. They cite Grafström, Lundström and Schelin (2012) by its DOI. The README’s table of designs gives the size of adesign_certainty()sample as the rows above the threshold plusrest’s, where it saidrest’s own. -
?joint_prob,?design_systematic,?ht_total,?as_svydesign,?design_stratifiedand the estimation article say that a systematic sample has no design-unbiased variance estimator at a step of 2 rows or more, where neighbouring rows are never drawn together. Withnabove half the rows walked, every pair of rows has a positive joint probability.?design_stratifiedgave two rows of a stratum less than a step apart a joint probability of 0; that holds for rows at mostN_h / n_h - 1apart, and at a step of 3.33 rows two rows 3 apart are drawn together one time in five.?design_systematicsays thatas_svydesign()refuses a replicated sample with a replicate that drew no rows. The estimation article’s sections on systematic samples no longer use one letter for both a row and the interval, and the README’s table of designs gives the successive-difference variance ofdesign_stratified(within =).
drawn 0.2.0
An adversarial review of 0.1.0 found estimates that were wrong without saying so. Every fix below was reproduced by simulation first, and each now has a test that fails on the old behaviour.
Wrong answers, fixed
-
One sampled row per stratum reported a variance of 0. Sen-Yates-Grundy has no within-stratum pair to sum over, so a stratified sample with one row in every stratum printed a standard error of exactly zero and a zero-width interval.
ht_total()andht_mean()now decline with the reason, assurveydoes by default, for strata and fordesign_temporal()intervals. -
A stratum allocated no rows silently biased the total. Proportional allocation gives nothing to a stratum smaller than about
N / n, and Neyman allocation gives nothing to one whose auxiliary variable is constant. Its rows then have probability 0 and drop out of every estimate; one example was 84% low.draw()now warns, naming the strata and the fix. The documentation previously claimedmin_per_stratum = 0“leaves allocation unbiased” and that a floor biases a total; both were wrong, and are corrected. -
The jackknife ignored strata. It deleted rows across the whole sample, counting the differences between strata as sampling variance: sixty times too large on a well-stratified frame. It is now the stratified (JKn) jackknife, and equals the analytic figure exactly for
design_stratified()anddesign_temporal(). -
One row per cluster understated a multistage variance by ~30%. The exact two-stage estimator cannot see within-cluster variation when only one row is taken per cluster. It now declines, and
variance = "auto"falls back to the delete-a-cluster (ultimate-cluster) jackknife. -
Neyman allocation abandoned its own rule when a stratum was capped. The surplus from a stratum too small for its share was dealt out round-robin; it is now re-split in proportion to
size * sd, as in Cochran (1977, 5.9). -
ht_mean(estimator = "ht")printed itself as a Hajek mean. -
design_systematic(order_by = )returned rows in sorted order, breaking the documented promise that rows come back in frame order. - The documentation for
design_weighted(method = "systematic")said some pairs of rows can never be drawn together and pointed tosampling::UPsystematicpi2()for joint probabilities. The rows are shuffled before the walk, so every pair can co-occur and that function answers a different design.
Variance estimators from the literature
Every estimate now reports which estimator produced its variance in method, and names any approximation when it prints.
-
Confidence intervals use t on the design’s degrees of freedom — primary sampling units minus strata (Korn and Graubard 1999), matching
survey::degf(). At four clusters the normal interval covered about 87%; the t interval restores nominal coverage.df = Infgives the normal interval. -
Systematic PPS uses Deville’s (1999) approximation, which needs only first-order probabilities and scales each row by its own
1 - pi. It equalssampling::varest()exactly and tracks the empirical variance at 0.98, where the previous jackknife ran at 0.89. -
Systematic samples get the successive-difference approximation (Wolter 2007) rather than no variance at all. On a frame sorted by something related to
yit stays near the truth where the simple random formula overstates two- to thirtyfold. Its limits — a cycle matching the interval, or a trend so smooth the random start is the only variation — are documented.
New
-
design_spread()draws a spatially balanced sample by the local pivotal method (Grafström, Lundström and Schelin 2012): exact first-order inclusion probabilities, equal or proportional tosize, with neighbours competing so the sample covers the space evenly. On a smooth surface its variance was 14–25% of a simple random sample’s. It spreads across any numeric columns, so it also balances a sample on covariates without choosing strata.ht_total()uses the local mean variance estimator (Stevens and Olsen 2003) for it. -
ht_total()andht_mean()takeby =for domain estimates computed from the whole sample rather than a subset of it. Standard errors matchsurvey::svyby()exactly. -
ht_mean()accepts a logicaly, so a proportion is one call. -
plot(design, data, type = "map")places every row by two columns and fills in the selected ones — the view that shows whether a sample covers the ground. - Key functions carry
@referencesto the methods they implement.
Handing off to survey
- Multistage designs are expressed as two stages, so
survey’s standard error now matchesht_total()exactly; it previously differed by up to 5–10%. - Systematic PPS, alone or as a certainty design’s
rest, maps topps = "brewer"and agrees withht_total()within 0.2%. - A reservoir capped by
max_itemsuses the rows the stream reached as its population, not the whole frame.
Documentation and site
- The README is generated from
README.Rmd, so every output shown is real. - New articles: a getting-started walkthrough, how the estimates work (every estimator, its reference and its simulation check), an audit-sampling walkthrough, and a spatially balanced field survey.
-
graphicsandutilsare declared inImports.
drawn 0.1.0
First release.
Designs are objects
Sampling is expressed as a design you build and then apply, rather than a function call with the design buried in its arguments:
plan <- design_stratified(strata = "site", n = 500)
draw(data, plan, seed = 1)A design can be printed, stored, reused across data sets, and — the part that matters for estimation — asked what it does before you draw anything.
Eleven designs ship: design_simple(), design_stratified(), design_systematic(), design_cluster(), design_multistage(), design_weighted(), design_certainty(), design_reservoir(), design_bootstrap(), design_temporal() and design_spatial().
design_certainty() composes: rows at or above a threshold are all taken, and any other design is applied to what remains. That is the standard shape of an audit sample, and the cheapest way to cut variance when a few units dominate a total. Certainty rows have inclusion probability exactly 1, so they contribute their own value with a weight of 1 and add nothing to the variance; inclusion and joint probabilities compose exactly across the two parts.
One contract across all of them
-
nis always the total number of rows drawn, never a per-group figure.design_temporal()usesper_intervalprecisely because that one is per group. -
allocationalways says how a total is split across groups. -
na_rmalways decides whether missing keys are dropped or raise an error, and means the same thing whether you are drawing or asking for probabilities. -
replacealways rules outweights = TRUE: an inclusion probability describes distinct units, and a sample holding duplicates cannot be weighted by one. -
draw()restores the caller’s random number stream before returning, so sampling inside a simulation does not shift the simulation’s own draws. - What comes back has the same class and the same columns, in the same order, as what went in — tibble in, tibble out, with or without weights. Rows come back in frame order except where draw order is meaningful:
design_simple()anddesign_weighted()return draw order, anddesign_bootstrap()returns replicates behind a leading.replicatecolumn.
Inclusion probabilities and estimation
inclusion_prob() gives the first-order inclusion probability of every population row under a design, without drawing anything — a quick way to check a plan before committing to it. draw(weights = TRUE) attaches those probabilities and the corresponding design weights to a sample as .prob and .weight.
joint_prob() gives second-order probabilities, and ht_total() and ht_mean() use them to return an estimate with a standard error and confidence interval:
s <- draw(pop, design_stratified("site", n = 40), seed = 1, weights = TRUE)
ht_total(s, "spend")
ht_mean(s, "spend")ht_mean() defaults to the Hajek estimator, sum(y/pi) / sum(1/pi), which divides by the estimated population size rather than the known one; estimator = "ht" divides by the true N. The two coincide exactly whenever the weights of the drawn rows sum to N — every fixed-size equal-probability design, and every stratified design without replacement — and part company when the sample size is random or the weights vary within a fixed-size sample. Hajek is usually the steadier of the two, which is why it is the default; ?ht_mean sets out when it is not, and why "ht" is unbiased only where every row is reachable.
deff() reports the design effect on either result — the design’s variance against simple random sampling of the same size, which reads as an exchange rate on sample size. Stratifying on a variable that matters can put it far below 1; clustering on the same variable puts it well above.
The variance estimator matches how each design randomises: Sen-Yates-Grundy for fixed-size designs, the independent-units form for Poisson sampling, the cluster-level form for cluster designs — whose row count is random whenever clusters differ in size — and, for a certainty design, whatever rest uses, since certainty rows are in every possible sample and contribute nothing.
Where a design has inclusion probabilities but no closed-form joint ones, ht_total() falls back to a delete-a-group jackknife and reports which method it used, or "none" where neither could produce a figure. The jackknife is declined for systematic sampling, which has a single primary sampling unit, and for Poisson sampling, which has an exact variance already.
Every analytic estimator is checked in the test suite against the empirical sampling variance of its own estimator, every inclusion and joint probability against the observed frequency over thousands of draws, and every design that survey can express against survey::svytotal().
Planning a sample, and checking one
plan_size() solves for n given the precision wanted, rather than asking for a guess. It takes a margin of error and a measure of spread, and applies three corrections: a finite population correction from N, an inflation for the design from deff, and an inflation for non-response from response. It works for a mean, a proportion or a total, and says so plainly when the margin asked for is unreachable by sampling.
plan_size(margin = 5, sd = 40, N = 20000, deff = 2.5, response = 0.7)sample_summary() reports what was drawn against what was there: the sampling fraction, the range and coefficient of variation of the design weights, the per-stratum or per-cluster counts against the frame, and the number of rows the design could never have reached.
Handing off to the survey package
as_svydesign() builds a survey::svydesign() object from a drawn sample, so the analysis this package does not do — subpopulation estimates, regression, calibration, quantiles with proper standard errors — can be done by the package that does.
The two packages compute variance from different starting points: this one from the design’s joint inclusion probabilities, survey from the design’s shape. Each design is therefore expressed in survey’s own terms — strata for a stratified or temporal design, cluster ids for a cluster design, survey::poisson_sampling() for Poisson, and a taken-whole stratum for the certainty rows. Totals and standard errors then agree to floating point for every design but two: survey uses the ultimate-cluster approximation for multistage designs, and returns the conservative simple-random figure for systematic sampling where ht_total() declines to return one. ?as_svydesign has the table. Compositions with no single survey equivalent — a certainty design over a cluster, multistage or Poisson rest — are refused rather than approximated.
Seeing a design
plot(design, data) shows which rows a design selects — every frame row as a dot, selected ones filled in — and type = "probability" plots inclusion probability against frame position. Base graphics, no plotting dependency.
Allocation
design_stratified() accepts allocation = "neyman" with allocation_by, giving strata shares proportional to size * sd. That minimises the variance of a total for a fixed n by putting more rows where the values vary most.
Saying when it cannot
Not every design has a closed-form inclusion probability, and the ones that don’t report that rather than returning an approximation:
-
design_cluster(balanced = TRUE)— the per-cluster take is the smallest selected cluster’s size, which is random. -
design_multistage(allocation = "proportional")— the second-stage allocation depends on which clusters were selected. -
design_multistage()where the per-cluster take is not constant —nnot divisible byn_clusters, or a cluster smaller thann / n_clusters. The allocation runs over the selected clusters, so a row’s probability depends on which others were drawn. -
design_weighted(method = "successive")— successive sampling has no closed form. This is the default, and the reason the other two methods exist. -
design_bootstrap()— resampling a sample is not a probability sample of a finite population.
simulate = TRUE estimates any of them by Monte Carlo, for first-order probabilities and, in joint_prob(), for second-order ones — which is the general answer where no formula exists, including design_weighted(method = "systematic"), whose joint probabilities depend on the order units are visited. design_bootstrap() is the one exception, and simulating it is refused: every row appears in some replicate, so the count converges to 1 for all of them. Systematic sampling has first-order probabilities but no design-unbiased variance at all, because most pairs of rows can never co-occur; ht_total() says so instead of returning a number.
Probability proportional to size
design_weighted() offers three methods, and they are not interchangeable:
method |
Inclusion probabilities | Sample size |
|---|---|---|
"successive" (default) |
Not proportional to weight, no closed form | Fixed |
"systematic" |
Exactly n * p_i
|
Fixed |
"poisson" |
Exactly n * p_i
|
Random, mean n
|
The default is what base::sample(prob = ) does: a good way to bias selection toward heavy units, but the weights govern each sequential draw rather than the probability of ending up in the sample. Use "systematic" or "poisson" when the sample will be estimated from. Units heavy enough that n * p_i > 1 are taken with certainty and the remainder rescaled, iterating until every probability is valid.
Notes
-
sfis a suggested dependency, needed only bydesign_spatial(), andsurveyonly byas_svydesign(). Nothing else requires either. - Under spherical geometry a longitude/latitude polygon whose edge spans more than 180 degrees is drawn the short way across the antimeridian, so a “whole world” rectangle collapses to a narrow strip.
design_spatial()warns when a region has such an edge. - Reservoir sampling takes a vectorised path for a data frame, whose length is already known, and Algorithm L for a genuine stream — a connection or a generator function.
- Calendar units in
design_temporal()step by calendar months and years, not by fixed 30.44-day durations.