Skip to contents

Examples

Overall, CopyCat has three different code sources. First, CopyCat comes with data from the cheat sheets. Of course, you can use your own code snippets as well. Second, CopyCat can also fetch and copy code for you that lives on Github. Ultimately, CopyCat searches also within the R help files, vignettes or on GitHub for code that illustrates how a function works.

I don’t know how many times I searched my old scripts, especially for a ggplot code snippet, but I have forgotten the details about this little piece of worl. For this reason, I started to create this package. CopyCat comes with a small data set (CopyCatCode) that contains minimal examples of several cheat sheet examples that run without further ado. For example, let’s have a look at code examples for the ggplot2 package. The CopyCatCode data provides the package name, the function, and the code of a minimal example:

## load library and provide a data frame 
library(copycat)

CopyCatCode %>% 
  filter(package == "ggplot2") %>% 
  arrange(fct)
#> # A tibble: 43 × 3
#>    package fct          code                                                    
#>    <chr>   <chr>        <chr>                                                   
#>  1 ggplot2 annotate     "ggplot(mtcars, aes(x=mpg)) +   \r\n  geom_histogram(co…
#>  2 ggplot2 facet_grid   "ggplot(mtcars, aes(hp, mpg)) + \r\n  geom_blank() + \r…
#>  3 ggplot2 facet_wrap   "ggplot(mtcars, aes(hp, mpg)) + \r\n  geom_blank() + \r…
#>  4 ggplot2 geom_abline  "ggplot(mpg, aes(cty, hwy))+\r\n  geom_point()+\r\n  ge…
#>  5 ggplot2 geom_area    "ggplot(mpg, aes(hwy))+\r\n  geom_area(stat = \"bin\")" 
#>  6 ggplot2 geom_bar     "ggplot(data=mpg, aes(x=class)) + geom_bar()"           
#>  7 ggplot2 geom_bin_2d  "ggplot(diamonds, aes(carat, price))+ geom_bin2d(binwid…
#>  8 ggplot2 geom_boxplot "ggplot(diamonds, aes(x=color, y=carat, fill=color)) +\…
#>  9 ggplot2 geom_col     "ggplot(diamonds, aes(x=color, y=carat)) +\r\n  geom_co…
#> 10 ggplot2 geom_contour "ggplot(faithfuld, aes(waiting, eruptions, z = density)…
#> # ℹ 33 more rows

Let’s say you cannot remember how pivot_longer from the tidyr package works. Just search for the corresponding code snippet via the copycat() function, it searches the code snippet and copies the returned code to your clipboard. To see which code is returned, use the corresponding copycat_code() function.

# copycat("pivot_longer") saves the returned code to the clipboad
#>[1] "Your code: relig_income %>% tidyr::pivot_longer(!religion, names_to = #>'income', values_to = 'count')"
# copycat_code() let us inspect what the function returned 
copycat_code("pivot_longer")

Since the code is based on implemented data – as all examples listed in CopyCat – you can see how a function works by pasting it into your console. Alternatively, set the run option to TRUE and copycat() sends the code to your console.

copycat("pivot_longer", run = T )
relig_income %>% 
  pivot_longer(!religion, names_to = 'income', values_to = 'count')
#> # A tibble: 180 × 3
#>    religion income             count
#>    <chr>    <chr>              <dbl>
#>  1 Agnostic <$10k                 27
#>  2 Agnostic $10-20k               34
#>  3 Agnostic $20-30k               60
#>  4 Agnostic $30-40k               81
#>  5 Agnostic $40-50k               76
#>  6 Agnostic $50-75k              137
#>  7 Agnostic $75-100k             122
#>  8 Agnostic $100-150k            109
#>  9 Agnostic >150k                 84
#> 10 Agnostic Don't know/refused    96
#> # ℹ 170 more rows

Of course, the minimal examples will only run if the package has been loaded and most of the time we know the package name. However, sometimes we have to look up the package name if we do not use a function often. The copycat_package() function returns the corresponding package name and sends the code library(...) directly to your console. The copycat_package() function copies the code also to the clipboard, since you want to insert it into your script as well.

#search for a package name, copies the load and loads the library
copycat_package("pivot_longer")
#>[1] [1] "Mission accomplished, loaded and copied library: tidyr"

If you add typos by accident, if you are not sure whether the function is written in small or large caps, you might be lucky and a similar match is found in the data.

#typos and other mistakes 
copycat_package("bivot")
#> [1] "Did you mean pivot_longer from the tidyr package?"
#> [2] "Did you mean pivot_wider from the tidyr package?"

Unfortunately, this only works if a match is found at all.

copycat("bivatasa")
#>[1] "Sooorry, I've got no idea what you are looking for!"

Github

CopyCat can also be connected to your Github repository to copy one of your old scripts. First, you have to setup the Github account details, that CopyCat needs to search. Provide the name of the author, the repository, and the branch name.

git_setup <- c(author = "edgar-treischl",
               repository = "Graphs",
               branch = "main")

The copycat_gitsearch() function uses the Github API to search within your repository and shows all R scripts that live within the repository.

copycat_gitsearch()
#> # A tibble: 2 × 1
#>   git_scripts  
#>   <chr>        
#> 1 R/ggplots.R  
#> 2 R/plotgraph.R

The copycat_git() function copies the code of a script to your clipboard.

copycat_git("datasaurus")
#>[1] "Mission accomplished!"

And opycat_gitplot("datasaurus") sends the code to your console.

Help files and vignettes

Often, all we need is code that runs to see how a functions work. For this reason, CopyCat to search within the R help files and vignettes, but returns only the code listed in the vignette or the examples of the help file. The copycat_helpsearch() function list all help files of a package:

copycat_helpsearch("tidyr")
#>  [1] "billboard"              "check_pivot_spec"       "chop"                  
#>  [4] "cms_patient_experience" "complete"               "construction"          
#>  [7] "deprecated-se"          "drop_na"                "expand"                
#> [10] "expand_grid"            "extract"                "extract_numeric"       
#> [13] "fill"                   "fish_encounters"        "full_seq"              
#> [16] "gather"                 "hoist"                  "household"             
#> [19] "nest"                   "nest_legacy"            "pack"                  
#> [22] "pipe"                   "pivot_longer"           "pivot_longer_spec"     
#> [25] "pivot_wider"            "pivot_wider_spec"       "reexports"             
#> [28] "relig_income"           "replace_na"             "separate"              
#> [31] "separate_longer_delim"  "separate_rows"          "separate_wider_delim"  
#> [34] "smiths"                 "spread"                 "table1"                
#> [37] "tidyr-package"          "tidyr_data_masking"     "tidyr_legacy"          
#> [40] "tidyr_tidy_select"      "uncount"                "unite"                 
#> [43] "unnest"                 "unnest_auto"            "unnest_longer"         
#> [46] "unnest_wider"           "us_rent_income"         "who"                   
#> [49] "world_bank_pop"

And the copycat_help() function copies the examples section of a help file to your clipboard. Or use the example function from base R to inspect them in the console.

#example saves examples of the online help files into your clipboard
example("drop_na", package = "tidyr")
#> 
#> drop_n> df <- tibble(x = c(1, 2, NA), y = c("a", NA, "b"))
#> 
#> drop_n> df %>% drop_na()
#> # A tibble: 1 × 2
#>       x y    
#>   <dbl> <chr>
#> 1     1 a    
#> 
#> drop_n> df %>% drop_na(x)
#> # A tibble: 2 × 2
#>       x y    
#>   <dbl> <chr>
#> 1     1 a    
#> 2     2 NA   
#> 
#> drop_n> vars <- "y"
#> 
#> drop_n> df %>% drop_na(x, any_of(vars))
#> # A tibble: 1 × 2
#>       x y    
#>   <dbl> <chr>
#> 1     1 a

The same function exist to search for and copy code from vignettes. The copycat_vigsearch() returns all available vignettes of a package.

copycat_vigsearch("tidyr")
#> [1] "in-packages.R" "nest.R"        "pivot.R"       "programming.R"
#> [5] "rectangle.R"   "tidy-data.R"

And copycat_vignette() copies the script.

copycat_vignette("tidyr", "pivot")

To copy smaller code chunks to your clipboard is fine. Help files and vignettes are much longer. Therefore, we may want to create a new file and paste the code into a new file. The copycat_helpscript()create a new R script and copies the examples of the help file into that script, while copycat_vigscript() does the same with the code from the vignette.

copycat_helpscript("tidyr", "pivot")
copycat_vigscript("tidyr", "pivot")

CopyCat has started as a personal package. Feel free to use it or manage your own code snippets with it. Just add your data frame with the same variable names of the small example data (CopyCatCode) and CopyCat handles your own snippets.