Skip to content

withr

Run Code 'With' Temporarily Modified Global State

v3.0.2 · Oct 28, 2024 · MIT + file LICENSE

Description

A set of functions to run code 'with' safely and temporarily modified global state. Many of these functions were originally a part of the 'devtools' package, this provides a simple package with limited dependencies to provide access to these functions.

Downloads

1.5M

Last 30 days

11th

5.6M

Last 90 days

17.1M

Last year

Trend: -19.4% (30d vs prior 30d)

CRAN Check Status

1 ERROR
13 OK
Show all 14 flavors
Flavor Status
r-devel-linux-x86_64-debian-clang OK
r-devel-linux-x86_64-debian-gcc OK
r-devel-linux-x86_64-fedora-clang OK
r-devel-linux-x86_64-fedora-gcc OK
r-devel-macos-arm64 OK
r-devel-windows-x86_64 OK
r-oldrel-macos-arm64 OK
r-oldrel-macos-x86_64 OK
r-oldrel-windows-x86_64 OK
r-patched-linux-x86_64 OK
r-release-linux-x86_64 OK
r-release-macos-arm64 OK
r-release-macos-x86_64 ERROR
r-release-windows-x86_64 OK
Check details (2 non-OK)
ERROR r-release-macos-x86_64

examples

Running examples in ‘withr-Ex.R’ failed
The error most likely occurred in:

> ### Name: with_db_connection
> ### Title: DBMS Connections which disconnect themselves.
> ### Aliases: with_db_connection local_db_connection
> 
> ### ** Examples
> 
> db <- tempfile()
> with_db_connection(
+   list(con = DBI::dbConnect(RSQLite::SQLite(), db)), {
+     DBI::dbWriteTable(con, "mtcars", mtcars)
+ })
Error in loadNamespace(x) : there is no package called ‘pkgconfig’
Calls: with_db_connection ... loadNamespace -> withRestarts -> withOneRestart -> doWithOneRestart
Execution halted
[1] "two"
[1] "one"
Ran 2/2 deferred expressions
ERROR r-release-macos-x86_64

tests

Running ‘testthat.R’ [7s/11s]
Running the tests in ‘tests/testthat.R’ failed.
Complete output:
  > library(testthat)
  > library(withr)
  > 
  > test_check("withr")
  [ FAIL 0 | WARN 0 | SKIP 5 | PASS 376 ]
  
  ══ Skipped tests (5) ═══════════════════════════════════════════════════════════
  Error in base::nchar(wide_chars$test, type = "width") : 
    cannot open file '/Volumes/Builds/packages/big-sur-x86_64/Rlib/4.5/cli/R/sysdata.rdb': No such file or directory
  Calls: test_check ... unicode_pre -> setup_unicode_width_fix -> <Anonymous>
  Execution halted
  No deferred expressions to run
  No deferred expressions to run

Check History

ERROR 13 OK · 0 NOTE · 0 WARNING · 1 ERROR · 0 FAILURE Mar 10, 2026
ERROR r-release-macos-x86_64

examples

Running examples in ‘withr-Ex.R’ failed
The error most likely occurred in:

> ### Name: with_db_connection
> ### Title: DBMS Connections which disconnect themselves.
> ### Aliases: with_db_connection local_db_connection
> 
> ### ** Examples
> 
> db <
...[truncated]...
cars", mtcars)
+ })
Error in loadNamespace(x) : there is no package called ‘pkgconfig’
Calls: with_db_connection ... loadNamespace -> withRestarts -> withOneRestart -> doWithOneRestart
Execution halted
[1] "two"
[1] "one"
Ran 2/2 deferred expressions

Reverse Dependencies (1090)

imports

ARUtools CDMConnector DBItest DIscBIO DamageDetective DescTools DisaggregateTS DiscreteTests DominoDataR ECMLE EMJMCMC EcotoneFinder FSA FastRet FourWayHMM GDPuc GSODR GeoModels IBLM IceSat2R ImpactEffectsize L1centrality MAINT.Data MatrixHMM MatrixMixtures OmicsPLS OpenRepGrid.ic OpenSourceAP.DownloadR Orangutan PL94171 PopPsiSeqR PopulateR RDHonest RFishBC RKaggle ROOT RPostgres Rdistance ResultModelManager Rgff Rigma SSN2 SSNbler SelectBoost.beta SimKid Spectran TSdisaggregation TernTables TestGenerator admiraldev adproclus amregtest anyLib argminCS artma asciicast attachment baguette bambooHR batchtools bbw bigPCAcpp biomartr biplotEZ bmm bonsai booami box.linters boxr btw bundle buoyant caret casimir checkhelper chromote circacompare citation cliapp cloudml clusterMI coglasso compdb condathis connector.databricks covr cpp4r cucumber customiser cyclocomp dRiftDM dataquieR dbplyr deident delma details detrendr devtools dfeR dials discrim docorator downlit duckspatial easyEWAS ebvcube edwards97 embed exampletestr excursions eyeris f1dataR fake fakir fgeo.analyze filesstrings fkcentroids fledge flippant flipr flocker fmesher forecast frscore galaxias gargle geotargets getRad ggdist ggfacto ggforce ggimage ggincerta ggplot2 ggraph ggrepel ggridges ggstance ghclass gms goodpractice googledrive googlesheets4 goxygen gratia hdcuremodels henna hfhub historicalborrowlong httr2 important indiedown infer injurytools inlabru irace iraceplot isoorbi jagstargets jamba labNorm laminr lang lavDiag learnr logr madrat meetupr metabodecon metamorphr metaumbrella midi mixvlmc ml mlflow mlr3inferr mlr3oml mlr3torch mockr modeltime.resample monolix2rx mrgsim.sa multilevelmod multivarious muttest nandb narfima natmanager neuromapr nevada nipnTK nlmixr2auto normref npiv odin oldr opencage oppr orderly ordinalsimr parsermd parsnip parzer personalr phsmethods pins pkgdown pkgstats player pmparser ppsr precommit precrec prioritizr probably procs prodigenr proffer profile pysparklyr qgisprocess qualtRics racademyocean ragnar raptr raws.profile rayrender rayvertex rcmdcheck rdecision read.abares readr readtextgrid recipes reporter reprex reticulate reviser rex rextendr rgoogleads rhino rirods rmcmc rollama ropenblas roxygen2 rsurveycto rytstat sccore scov selenider sffdr sharp shiny shinylive shinytest shinytest2 singcar sixtyfour slackr snpAIMeR spCF sparklyr sqltargets statsExpressions streamy styler surveyvoi susographql syrup tabnet tarchetypes tatoo teal.logger test.assessr testthat tfevents thamesmix themis thinkr tidybayes tidypaleo tidyselect torch torchdatasets torchvision torchvisionlib traudem tune twbparser typetracer usedthese usethis vayr vecmatch vetiver vitals vol2birdR vroom vsp wdpar webdriver whep whirl wither workflows workflowsets worldfootballR xpectr yardstick ymlthis

suggests

Achilles AllelicSeries BAQM BCEA BGmisc BLMEngineInR BiocManager CBTF CNVreg CatastRo Characterization CimpleG CohortCharacteristics CohortGenerator CohortMethod CommonDataModel Cubist DataPackageR DatabaseConnector DeSciDe DiagrammeR Dire DistributionIV EDCimport EGM EdSurvey EpiNow2 Eunomia FSelectorRcpp FakeDataR FeatureExtraction GCubeR GLMMcosinor GUTS GenoPop GitAI GitStats Goodreader IRdisplay InterpolateR IsoriX JSmediation JWileymisc LATERmodel LISTO MGMM MicroMoB MiscMetabar MolgenisArmadillo NHSRplotthedots NetLogoR OlinkAnalyze OmopSketch OncoBayes2 PFW PHEindicatormethods PKNCA PaRe PatientLevelPrediction PatientProfiles PhilipsHue PiC PlotFTIR PracticalEquiDesign PublicationBias R4GoodPersonalFinances RAQSAPI RBesT RCTRecruit RDP REDCapTidieR RMariaDB RNOmni RPresto RSQLite Rapp RcensusPkg RcppPlanc Require Rsearch Rttf2pt1 S7schema SCDB SCIproj SCpubr SDMtune SIAtools SVEMnet SelfControlledCaseSeries SimNPH SkeletalVis SomaDataIO SpaDES.core SpaDES.tools SportMiner StanHeaders StatsTFLValR Surrogate SurrogateRegression TBox TSCI Temporal Tplyr TractorTsbox TreatmentPatterns TriLLIEM TrialEmulation VIM WeMix XLConnect a5R aNCA aboveR adbcdrivermanager adbi admiral admiralonco admiralophtha adnuts aedseo afcharts affiner airnow aisdk alcyon altdoc amadeus ami anabel and ankiR anybadger arl armadillo4r arrow artpack askgpt assertions asympDiag auk autoslider.core auxvecLASSO avesperu avstrat babelmixr2 baizer bartMachine baselinenowcast basepenguins bayestestR bcdata bcmaps bench bidux bigPLSR bigrquery bioLeak bioRad biometryassist bit64 bittermelon blastula blockr blockr.core blockr.dock blvim bookdown bootPLS box.lsp brand.yml brickster brightspaceR brmsmargins bsicons bskyr bslib bsplus c060 cabinets callr camcorder camtrapR canaper captain cards cardx caretSDM caugi causalDisco causalOT cereal chattr checked chevron chk chopin chores ciecl circle clarify cli cliff climatehealth clinicalfair clinify clinpubr clock cloudfs codemetar collapse cometr command condGEE confcons config configulaR conflicted congress connectapi connectcreds connector connectwidgets constructive contactsurveys containr copernicusR corella corrtable couplr coursekata covtracer cowfootR cpmr cpp11 cpp11armadillo cpp11eigen cramR crane cranlike crayon crmPack crossmap crosstable crul crunch ctlr cvasi data.validator datacommons datarobot datasetjson datawizard date4ts datefixR dbi.table dcmstan debugme deduped deeptime delimtools desc diffdf diseasystore distill dittodb dm dockViewR dockerfiler dotprofile dpkg dplyr dtlg dtmapi duckdb duckplyr dunlin dverse eaf easystats ebirdst ebx echarts4r econid ediblecity educabR egnyte ellmer emburden emodnet.wfs encryptr envsetup envvar epidatr epidict epiviz ergm evaluate excluder extrafont extras exuber fakemake fastbioclim fastfocal fastml fastreg fauxnaif fcall fdacluster fdasrvf featureflag ffscrapr fiery fig filebin filecacher fioRa flashr flexsiteboard flextable flir flowchart fluxfinder fmriAR foghorn fontcm forcats forcis formatters foundry fr fracture framework fred friendlynumber froggeR frontmatter fs fusen fy gander geeLite generics geojsonio ggExtra ggPMX ggdag ggeffects ggpedigree ggpointless ggspatial ggstatsplot ggsurvfit ggthemes ggtibble ggvegan gh gibasa gips giscoR gitcreds gitdown gitr glue gmailr gmoTree gofigR golem gptstudio grafzahl grainscape grattan grattanInflators gsClusterDetect gt gtexr gtsummary guildai gutenbergr hakaiApi halfmoon handwriter hardhat hdf5r.Extra healthdb here hexsession hippie hmde hmstimer htmltools hutils hutilscpp hypothesis iai ibawds icecream igraph imfweo incidence2 incubate inshiny insight instantiate ipumsr jentre jetpack jollofR joyn jsonvalidate kanjistat keras keras3 keyring knitrProgressBar kvkapiR lambdr languageserver legendry lifecycle lightr lineagefreq lintr liteq logger logrx lorem lpanda luz lvmisc maestro magclass mailmerge makepipe mall mantis mapSpain maraca marginaleffects mark maskr matrixset mccount mcmcr mcptools md4r measr melt meteospain metricminer mfcurve minSNPs miniCRAN miniPCH minorparties minty misha mlr3fda mlr3filters mlr3spatiotempcv mmequiv mmrm mockthat modelbased moocore mooplot move2 mregions2 mtaOpenData mtdesign mtscr multidplyr multilevelcoda multinma musicMCT myrror nadir namedropR nanoarrow nanoparquet naryn nettskjemar neuralGAM nfl4th nhanesdata nhppp niarules nlmixr2 nlmixr2est nlmixr2extra nlmixr2lib nlmixr2plot nodbi nomisdata nonmem2rx ntfy nuggets nuts nysOpenData occupationMeasurement odbc odiffr officer ohvbd omopgenerics omophub onetime openairmaps openaq openmpp options orcidtr oskeyring osmextract otel otelsdk ottr packager packrat pacs pacta.multi.loanbook pairwiseLLM pak pakret palettes pandoc parafac4microbiome parameters parsedate parttime paws.common performance peruflorads43 petersenlab phinterval piggyback pillar pioneeR pixieweb pixr pizzarr pkgbuild pkgcache pkgdepends pkgload pkgnet pkgsearch plotly plu plumber plume pmxNODE polyMatrix postcard potools pracpac precondition predictNMB pregnancy prettycode primarycensored printtree processx progress prompt propensity prqlr prt ps pudu pxmake quadkeyr quallmer quarto querychat quickPlot r2dii.analysis rCISSVAE random.cdisc.data rappdirs rasciidoc rb3 rbcb rbmi rcdf rcloner rcompendium rcrisp rcrossref rdocdump readODS readapra readxl recforest redist remotes reproducible restatis revealjs rfacts rgrass rhub ricu riingo rio risk.assessr riskmetric rlang rlistings rmangal rmapshaper rmarkdown rnpn roahd rosm rotulador roxy.shinylive roxyglobals rprojroot rsample rsconnect rsi rstanemax rstudioapi rtables rtables.officer rtemis rticles rtoot rvec rversions rvertnet rxode2 s3 sacRebleu samplr santoku saros saros.base sasquatch sass scribe secret seekr selenium serocalculator sessioninfo sevenbridges2 shard shiny.emptystate shiny.fluent shiny.i18n shiny.react shiny.semantic shiny.telemetry shinyOAuth shinychat shinymodels shinyscholar shinystate siera sigugr simDNAmixtures sims sinew skimr snowflakeauth socialmixr soilFlux sooty sortable sov spanishoddata sparkxgb sparsevctrs spatialsample spicy sqlfluffr sqlm squat srcpkgs srcr ssdtools sship stacomirtools stacr standardlastprofile starburst starsTileServer statAfrikR stddiff.spark stepmetrics stevedore stopmotion summata survParamSim survex surveydata survinger svrep swag syncdr taylor teal teal.code teal.data teal.modules.clinical teal.modules.general teal.reporter teal.slice teal.transform teal.widgets tensorflow tern tern.gee tern.mmrm testex testthatdocs tf tfrmt tfruns tglkmeans thematic theorytools tibble tidycensuskr tidyna tidypredict tidyquery tidysq tidytlg tidytreatment tidytuesdayR tikatuwq tikzDevice tinkr tok tor transltr trud truncnormbayes tsg tufte updateme usmap usmapdata utf8 vaultr vcr vctrs vdiffr vegawidget videogameinsightsR vmTools vvbitwarden waldo washr waywiser wbids weatherOz weatherjoin webfakes webmockr wf whoami widr worcs workflowr worldbank wrds writeAlizer xplainfi xportr yaml12 yfinancer ypr zephyr zip

Dependency Network

Dependencies Reverse dependencies ARUtools CDMConnector DBItest DIscBIO DamageDetective DescTools DisaggregateTS DiscreteTests DominoDataR ECMLE EMJMCMC EcotoneFinder FSA FastRet FourWayHMM +1075 more reverse deps withr

Version History

new 3.0.2 Mar 10, 2026
updated 3.0.2 ← 3.0.1 diff Oct 27, 2024
updated 3.0.1 ← 3.0.0 diff Jul 30, 2024
updated 3.0.0 ← 2.5.2 diff Jan 15, 2024
updated 2.5.2 ← 2.5.1 diff Oct 29, 2023
updated 2.5.1 ← 2.5.0 diff Sep 25, 2023
updated 2.5.0 ← 2.4.3 diff Mar 2, 2022
updated 2.4.3 ← 2.4.2 diff Nov 29, 2021
updated 2.4.2 ← 2.4.1 diff Apr 17, 2021
updated 2.4.1 ← 2.4.0 diff Jan 25, 2021
updated 2.4.0 ← 2.3.0 diff Jan 15, 2021
updated 2.3.0 ← 2.2.0 diff Sep 21, 2020
updated 2.2.0 ← 2.1.2 diff Apr 20, 2020
updated 2.1.2 ← 2.1.1 diff Mar 14, 2018
updated 2.1.1 ← 2.1.0 diff Dec 18, 2017
updated 2.1.0 ← 2.0.0 diff Oct 31, 2017
updated 2.0.0 ← 1.0.2 diff Jul 28, 2017
updated 1.0.2 ← 1.0.1 diff Jun 19, 2016
updated 1.0.1 ← 1.0.0 diff Feb 3, 2016
new 1.0.0 Sep 22, 2015