Code Monkey home page Code Monkey logo

reprex's Introduction

tidyverse

CRAN status R-CMD-check Codecov test coverage

Overview

The tidyverse is a set of packages that work in harmony because they share common data representations and API design. The tidyverse package is designed to make it easy to install and load core packages from the tidyverse in a single command.

If you’d like to learn how to use the tidyverse effectively, the best place to start is R for Data Science (2e).

Installation

# Install from CRAN
install.packages("tidyverse")
# Install the development version from GitHub
# install.packages("pak")
pak::pak("tidyverse/tidyverse")

If you’re compiling from source, you can run pak::pkg_system_requirements("tidyverse"), to see the complete set of system packages needed on your machine.

Usage

library(tidyverse) will load the core tidyverse packages:

You also get a condensed summary of conflicts with other packages you have loaded:

library(tidyverse)
#> ── Attaching core tidyverse packages ─────────────────── tidyverse 2.0.0.9000 ──
#> ✔ dplyr     1.1.3     ✔ readr     2.1.4
#> ✔ forcats   1.0.0     ✔ stringr   1.5.0
#> ✔ ggplot2   3.4.4     ✔ tibble    3.2.1
#> ✔ lubridate 1.9.3     ✔ tidyr     1.3.0
#> ✔ purrr     1.0.2     
#> ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
#> ✖ dplyr::filter() masks stats::filter()
#> ✖ dplyr::lag()    masks stats::lag()
#> ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors

You can see conflicts created later with tidyverse_conflicts():

library(MASS)
#> 
#> Attaching package: 'MASS'
#> The following object is masked from 'package:dplyr':
#> 
#>     select
tidyverse_conflicts()
#> ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
#> ✖ dplyr::filter() masks stats::filter()
#> ✖ dplyr::lag()    masks stats::lag()
#> ✖ MASS::select()  masks dplyr::select()
#> ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors

And you can check that all tidyverse packages are up-to-date with tidyverse_update():

tidyverse_update()
#> The following packages are out of date:
#>  * broom (0.4.0 -> 0.4.1)
#>  * DBI   (0.4.1 -> 0.5)
#>  * Rcpp  (0.12.6 -> 0.12.7)
#>  
#> Start a clean R session then run:
#> install.packages(c("broom", "DBI", "Rcpp"))

Packages

As well as the core tidyverse, installing this package also installs a selection of other packages that you’re likely to use frequently, but probably not in every analysis. This includes packages for:

  • Working with specific types of vectors:

    • hms, for times.
  • Importing other types of data:

    • feather, for sharing with Python and other languages.
    • haven, for SPSS, SAS and Stata files.
    • httr, for web apis.
    • jsonlite for JSON.
    • readxl, for .xls and .xlsx files.
    • rvest, for web scraping.
    • xml2, for XML.
  • Modelling

    • modelr, for modelling within a pipeline
    • broom, for turning models into tidy data

Code of Conduct

Please note that the tidyverse project is released with a Contributor Code of Conduct. By contributing to this project, you agree to abide by its terms.

reprex's People

Contributors

alistaire47 avatar assignuser avatar atusy avatar batpigandme avatar bisaloo avatar cderv avatar cwickham avatar hadley avatar jennybc avatar jimhester avatar juliasilge avatar krlmlr avatar lionel- avatar lorenzwalthert avatar marionlouveaux avatar markdly avatar mdlincoln avatar mrchypark avatar njtierney avatar olivroy avatar paternogbc avatar remlapmot avatar tappek avatar uribo avatar yutannihilation avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

reprex's Issues

Accept string input

From @jimhester in #36:

FWIW it would be nice if reprex() also accepted a pre-formatted string directly, like you get from clipr::read_clip().

blog post

draft one and put it in vignettes/releases/reprex-1.0.0

Re-indenting source

I'm about push something that changes how expression input is converted to a character vector. The leading whitespace can be suboptimal. To be clear, I'm not sure this is really new. The previous expression handling probably also mangled whitespace, just in a different way.

Bottom line: given source in a character vector or file, is there a way to re-indent it nicely?

@jimhester do you know?

paste reprex as folded block?

It would be nice to be able to paste a reprex into a github issue as a folded block.

The HTML is a little tricky to get right, but this could be addressed by incorporating it on the reprex side. I was thinking something like:

reprex(venue = 'gh', folded = TRUE)

Would you consider a PR?

formatting for SO

Hi Jenny.

First, thank you for the package, it is promising! I just used this package to post a question on stack overflow using the following code:

reprex({
  library(lme4)
  
  set.seed(101)
  
  sleepstudy$Subject <- as.character(sleepstudy$Subject)
  ss <- sleepstudy[sleepstudy$Subject == "308",]
  
  m1 <- lmer(Reaction ~ Days + (1 | Subject), ss)
}, venue = "so")

Since SO uses 4 spaces to make bloc code, I was wondering if the output in the preview pane could already include these 4 spaces so we can copy/paste directly on SO?

Happy new year,
Phil

Facilitate image upload and embedding

See my so post that I attempted to make with reprex(venue = "so") but the path hardcoding of the outputted .pngs does not currently work and so I have to upload each image manually. I realize this is early -- but very neat so far!

Better way of extracting string from expression

Here's a sketch from me and @wch

x <- quote({
  # This is a comment
  a +      b
})

src <- attr(x, "srcref")
src_1 <- src[[1]]
src_n <- src[[length(src)]]

lines <-  attr(src_1, "srcfile")$lines
lines <- lines[seq(src_1[1], src_n[3])]
lines[1] <- substring(lines[1], src_1[5] + 1, nchar(lines[1]))

if (lines[1] == "" || grepl("^\\s+$", lines[1])) {
  lines <- lines[-1]
}

process full-fledged Rmd

I wrote an answer for SO in the form of a full Rmd document for convenience, but knitr produces md not fullly compatible (code blocks, for one thing). It would be great if reprex included knitr hooks / rmarkdown custom flavoured md output format for SO. (there may well be one out there already, my memory and google haven't been very helpful). @yihui ?

Publicise RStudio snippets?

I just added this to my snippets file:

snippet reprex
    reprex::reprex({
      $1
    })

That way I can type reprex<tab> and get the full code block

Feature request: strip prompt from input

If my R console contains this:

> x <- rnorm(10)
> mean(x)
[1] 0.4189699

And I copy the first two lines so that my clipboard contains the following character string:

"> x <- rnorm(10)
> mean(x)"

And I call reprex(), then I get this as my output:

> x <- rnorm(10)
> mean(x)
#> Error: <text>:1:1: unexpected '>'
#> 1: >
#>     ^

A nice feature here would be to automatically strip out values of

options("prompt")
#> $prompt
#> [1] "> "

when they appear at the start of a newline.

Cool package!

Images

Images are one of the most difficult aspects of a reproducible example; they tend to stop an answer flow cold, as it involves saving an image, uploading it to something like Imgur, then pasting in a link to that.

Is there anything we can do to make this process easier? The ideal solution would be for knitr to upload generated figures to Imgur (which could be done with a custom knitr hook), but you need an API token to upload programmatically, which is an obstacle.

Perhaps at least the figures generated could be stuck in some easy-to-reach place so they can be uploaded.

(I know I've generated a pile of issues today; most of them are just for me to come back to later)

Don't overwrite infile

This causes foo.R to be overwritten by decorated version. Rename it?

reprex(infile = "foo.R", outfile = "foo")

Is not possible to find the function "construct_filename"

Hi,
I found your package very usefull, however, when you run code that produces plots they are not printed when you copy and past to stack overflow or github.

I might have some ideas on how to make this process easier for the user, generating url links to each plots automatically, so the final output will include the plots when pasted on online.

Can I fork this repo and suggest some changes?

I am also having some problems with the current dev version:

Error in reprex("teste.R") :
não foi possível encontrar a função "construct_filename"

Cheers,
Gustavo

de-reprex

If you copy reprex output from github or SO, there should be a function to strip out the #> lines and get just the code back.

reprex keyboard shortcut?

I'm not sure if this is a double up of #28, but I was thinking it would be really nifty to make a keyboard shortcut, so you could highlight some code, and then do something like Cmd + Shift + R and it would copy the text, then run reprex?

Thank you for writing a package I use almost every day!

unable to use xclip?

I used to be able to use reprex, but now for some reason it seems unable to use the clipboard, even though xclip is installed on my Ubuntu 16.04 machine. When I launch reprex() I get:

No input provided via `x` or `input` and clipboard is not available.

Any idea what might be going on? I'd be happy to provide any information you might need for debugging purposes. I'm using the last github version of reprex.

Add comment character parameter

Currently, if I run

reprex::reprex({x <- rnorm(100) ; mean(x)}, venue = 'gh', show = FALSE)

I get the code for

x <- rnorm(100)
mean(x)
#> [1] 0.06771625

which is wonderful! However, changing the comment character, e.g. to ## is more complicated, requiring (as suggested on Twitter) copying

#+ include=FALSE
knitr::opts_chunk$set(comment = '##')

#+ realstuff
x <- rnorm(100)
mean(x)

and then calling reprex::reprex() to get the code for

x <- rnorm(100)
mean(x)
## [1] 0.04698201

To make this process simpler, could we get a comment character parameter in reprex akin to formatR::tidy_eval's prefix?

Make it optional to operate in a tempdir

Why? Because I couldn't use reprex to do this:

getwd()
#> [1] "/Users/jenny/rrr/googlesheets"
rstudioapi::getActiveProject()
#> [1] "/Users/jenny/rrr/googlesheets"
devtools::package_file()
#> [1] "/Users/jenny/rrr/googlesheets"
testthat::test_path()
#> [1] "tests/testthat"
testthat::test_path("for_reference/gap_googlesheet.rds")
#> [1] "tests/testthat/for_reference/gap_googlesheet.rds"

setwd(testthat::test_path())
getwd()
#> [1] "/Users/jenny/rrr/googlesheets/tests/testthat"
testthat::test_path()
#> Error in if (!file.exists(path)) { : argument is of length zero
testthat::test_path("for_reference/gap_googlesheet.rds")
#> [1] "for_reference/gap_googlesheet.rds"

Generate .R output files

Per this twitter discussion, it would be useful to be able to generate an output .R file that is runnable but has outputs stored in comments.

One slight difference in the output will be that image links would have to be commented.

Create syntax-highlighted RTF snippets for pasting into, e.g., Keynote

I bet reprex could package this up nicely ... a gist tweeted by @AmeliaMN on code highlighting for Keynote presentations:

https://gist.github.com/jimbojsb/1630790

I'm going to paste the body here in case the gist goes away. But the comments look pretty useful, e.g. using alternative highlighters like Pygments..

Step 0:

Get Homebrew installed on your mac if you don't already have it

Step 1:

Install highlight. "brew install highlight". (This brings down Lua and Boost as well)

Step 2:

Highlight your source. "highlight -O rtf myfile.php | pbcopy". This will highlight the source code in RTF format and copy the result of that operation to your Mac's clipboard.

Step 3:

Paste into your slide in Keynote. Keynote will create a new text box with your highlighted code. You can adjust the width as needed, and adjust the font size with cmd+ and cmd-

import something from knitr

N  checking dependencies in R code
   Namespace in Imports field not imported from: ‘knitr’
     All declared Imports should be used.

clarification

in your readme

In theory, this is the domain of gistr, but people also tend to post .R or .Rmd and NOT resulting .md ... is there a gap in tools or is this just an unfortunate behavior pattern? I don't always want to render these files to see what someone's trying to show me.

but a .R or .Rmd file can go up un-rendered via gist_create() if you do knit=FALSE (which is the default)

Allow user to specify variables to be included as dput

One common thing users forget to do in a reproducible example is to share the variables they've already defined (for example, datasets they're working with). You can turn a variable into a reproducible chunk of code with dput.

If we already have a few variables defined, it would be good to be able to add them to the start of the reprex code automatically. Here's a hello-world version using lazy_eval:

define_vars <- function(...) {
  vs <- lazyeval::lazy_dots(...)

  varnames <- unname(sapply(vs, function(v) as.character(v$expr)))

  dputs <- sapply(vs, function(v) {
    v$expr <- substitute(capture.output(dput(x)), list(x = v$expr))
    lazyeval::lazy_eval(v)
  })

  paste(varnames, dputs, sep = " <- ")
}

This takes one or more variables as its arguments and turns them into code that defines those variables. For example:

a <- 1:5
d <- data.frame(a = 1:5, b = 2)

varcode <- define_vars(a, d)

# turns it into code
cat(varcode, sep = "\n")
#> a <- 1:5
#> d <- c("structure(list(a = 1:5, b = c(2, 2, 2, 2, 2)), .Names = c(\"a\", ", "\"b\"), row.names = c(NA, -5L), class = \"data.frame\")")

In the end version of reprex, I imagine having a vars function, which creates an argument suitable for passing in:

y <- 1:100
reprex({y + 2}, vars = vars(y))
# even though it wasn't included in the reprex, resulting code would start with
# y <- 1:100

Or just wrap with a list (though that takes a little expression-parsing internally to get the names out):

reprex({y + 2}, vars = list(y))

If you like this feature idea I'll add it to the next PR.

(Fun fact; after I finished this example I used reprex to share it. Works like a charm!)

session info

Might be nice to (optionally) include sessionInfo() or devtools::session_info() at the end

data.frame not found

I have this R code:

library(plm)
data(Grunfeld, package="plm")
class(Grunfeld)

copying to clipboard and executing reprex() yields:

library(plm)
data(Grunfeld, package="plm")
class(Grunfeld)
#> Error in eval(expr, envir, enclos): object 'Grunfeld' not found

Something very simple like mean(c(1:5)) works, also iris dataset works:

data(iris)
class(iris)
#> [1] "data.frame"

Maybe the wrong environment is referred to for dataset from packages?

Session info --------------------------------------------------------------------------------------------------------------------------------------------------------------
 setting  value                       
 version  R version 3.2.2 (2015-08-14)
 system   x86_64, mingw32             
 ui       RStudio (0.99.738)          
 language (EN)                        
 collate  German_Germany.1252         
 tz       Europe/Berlin               
 date     2015-10-28                  

Packages ------------------------------------------------------------------------------------------------------------------------------------------------------------------
 package   * version    date       source                         
 bdsmatrix   1.3-2      2014-08-22 CRAN (R 3.2.2)                 
 clipr       0.2.0      2015-10-06 CRAN (R 3.2.2)                 
 curl        0.9.3      2015-08-25 CRAN (R 3.2.2)                 
 devtools  * 1.9.1      2015-09-11 CRAN (R 3.2.2)                 
 digest      0.6.8      2014-12-31 CRAN (R 3.2.2)                 
 evaluate    0.8        2015-09-18 CRAN (R 3.2.2)                 
 formatR     1.2.1      2015-09-18 CRAN (R 3.2.2)                 
 Formula   * 1.2-1      2015-04-07 CRAN (R 3.1.3)                 
 htmltools   0.2.6      2014-09-08 CRAN (R 3.2.2)                 
 httr        1.0.0      2015-06-25 CRAN (R 3.2.2)                 
 knitr       1.11       2015-08-14 CRAN (R 3.2.2)                 
 lattice     0.20-33    2015-07-14 CRAN (R 3.2.2)                 
 magrittr    1.5        2014-11-22 CRAN (R 3.2.2)                 
 MASS        7.3-43     2015-07-16 CRAN (R 3.2.2)                 
 memoise     0.2.1      2014-04-22 CRAN (R 3.2.2)                 
 nlme        3.1-122    2015-08-19 CRAN (R 3.2.2)                 
 plm       * 1.4-0      2013-12-28 CRAN (R 3.2.2)                 
 R6          2.1.1      2015-08-19 CRAN (R 3.2.2)                 
 reprex    * 0.0.0.9001 2015-10-28 Github (jennybc/reprex@826ddf4)
 rmarkdown   0.8.1      2015-10-10 CRAN (R 3.2.2)                 
 sandwich    2.3-4      2015-09-24 CRAN (R 3.2.2)                 
 stringi     1.0-1      2015-10-22 CRAN (R 3.2.2)                 
 stringr     1.0.0      2015-04-30 CRAN (R 3.2.2)                 
 zoo         1.7-12     2015-03-16 CRAN (R 3.1.3)   

Can expression input NOT break #' and #+?

If put on the clipboard, this reprex code can exploit the usual knitr::spin tricks for text insertion and setting chunk options. Wonder if there's any way this could be retained for expression input?

#' ## Hey I'm a heading
(x <- 1:4)
#' blah blah
#+ eval = FALSE
y <- 2:5
x + y

yields this:

Hey I'm a heading

(x <- 1:4)
#> [1] 1 2 3 4

blah blah

y <- 2:5
x + y

Use tempfile by default, or have user specify outfile

Currently the function works in the current directory using a base filename along the lines of 08-25-2015_REPREX_gh. It keeps them there if outfiles = TRUE.

I suspect that:

  • Most users won't want to keep the input and output files, especially since the goal is to get it into GitHub or SO
  • Those that do would be at least as happy providing their own filename (so they can refer to it later); while they can specify

Thus, I'd propose working in a temporary file unless the user specifically provides an output file base (in which case the .R and .md will be appended). This saves some of the utility work in the reprex function, and lets the user choose the filename without being appended with a date.

reprex cannot generate a reprex of itself

reprex(reprex(1 + 1))

gives the error

 Error in env$metadata <- list() : 
    cannot change value of locked binding for 'metadata' 

(I wanted to reprex this example but I couldn't!!)

Demo of session info folded inside Details tag

Hello world

## a comment
(x <- 1:4)
#> [1] 1 2 3 4

hi again

y <- 2:5
x + y
#> [1] 3 5 7 9
Session info
devtools::session_info()
#> Session info -------------------------------------------------------------
#>  setting  value                       
#>  version  R version 3.3.1 (2016-06-21)
#>  system   x86_64, darwin13.4.0        
#>  ui       X11                         
#>  language (EN)                        
#>  collate  en_CA.UTF-8                 
#>  tz       America/Vancouver           
#>  date     2017-01-02
#> Packages -----------------------------------------------------------------
#>  package   * version     date       source                            
#>  backports   1.0.4       2016-10-24 cran (@1.0.4)                     
#>  devtools    1.12.0.9000 2017-01-02 Github (hadley/devtools@1ce84b0)  
#>  digest      0.6.10      2016-08-02 cran (@0.6.10)                    
#>  evaluate    0.10        2016-10-11 cran (@0.10)                      
#>  htmltools   0.3.5       2016-03-21 CRAN (R 3.2.4)                    
#>  knitr       1.15.1      2016-11-22 CRAN (R 3.3.2)                    
#>  magrittr    1.5         2014-11-22 CRAN (R 3.2.0)                    
#>  memoise     1.0.0.9001  2016-12-18 Github (hadley/memoise@884d565)   
#>  pkgbuild    0.0.0.9000  2016-11-22 Github (r-pkgs/pkgbuild@65eace0)  
#>  pkgload     0.0.0.9000  2016-11-22 Github (r-pkgs/pkgload@def2b10)   
#>  Rcpp        0.12.8.3    2017-01-02 Github (RcppCore/Rcpp@f0442a0)    
#>  rmarkdown   1.3         2017-01-02 Github (rstudio/rmarkdown@3276760)
#>  rprojroot   1.1         2016-11-15 Github (krlmlr/rprojroot@1745481) 
#>  stringi     1.1.2       2016-10-01 CRAN (R 3.3.0)                    
#>  stringr     1.1.0       2016-08-19 CRAN (R 3.3.0)                    
#>  withr       1.0.2       2016-06-20 cran (@1.0.2)                     
#>  yaml        2.1.14      2016-11-12 cran (@2.1.14)

Do something intelligent if imgur.com can't be reached

Right now, if I put this code on the clipboard:

plot(1:100)

and bring my internet connection down, I get this result:

> library(reprex)
> reprex()
 Show Traceback

 Rerun with Debug
 Error in reprex_(r_file, venue, show, upload.fun) : 
Cannot render this code. Maybe the clipboard contents are not what you think?
Error in function (type, msg, asError = TRUE)  : 
  Could not resolve host: api.imgur.com 

Get outfile base from infile

If input is given as foo.R, there should be a way to say that the base name for outfiles should be foo. Maybe by setting outfile = NA (vs the default of NULL or giving an actual value).

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.