Skip to content

Instantly share code, notes, and snippets.

@kaz-yos
Created October 12, 2017 15:51
Show Gist options
  • Save kaz-yos/b0634f47a9946c5dd17468b70c148063 to your computer and use it in GitHub Desktop.
Save kaz-yos/b0634f47a9946c5dd17468b70c148063 to your computer and use it in GitHub Desktop.
Switching from Base R to tidyverse
Taken from http://www.significantdigits.org/2017/10/switching-from-base-r-to-tidyverse/
| Base R command | Tidyverse Command | Comment |
|-----------------------------------+--------------------------------------------+---------------------------------------------------------------|
| read.csv() | read_csv() | also see read_delim(), read_tsv() and readxl::read_xlsx() |
| sort(), order() | arrange() | see also order_by() |
| mtcars$mpg = ... | mutate() | see also transmute() which drops existing variables |
| mtcars[,c(“mpg”, “am”)], subset() | select(), rename() | see also pull() |
| mtcars[mtcars$am == 1,], subset() | filter() | |
| aggregate() | summarise(), summarize(), do() | see also varaints like summarize_if() |
| ifelse() | if_else(), case_when() | see also near() |
| unique() | distinct() | |
| length(unique()) | n_distinct() | |
| sample(), sample.int() | sample_n(), sample_frac() | |
| all.equal() | all_equal() | |
| merge() | inner_join(), left_join() | see also right_join(), full_join(), semi_join(), anti_join() |
| rbind(), cbind() | bind_rows(), bind_cols() | |
| x >= left & x <= right | between() | see also near() |
| nrow(), sum() | tally(), count(), add_tally(), add_count() | |
| c() | combine() | |
| extends base R | cumall(), cumany(), cummean() | |
| mtcars$mpg[1,] etc | first(), last(), n(), top_n() | |
| split(), aggregate() | group_by() | see also ungroup() |
| intersect(), union() | intersect(), union() | |
| No equivalent command in base R | lead(), lag() | |
| ifelse(..., NA) | na_if() | |
| switch() | recode() | see also forcats package when dealing with factors |
| mtcars[3:5,] | slice() | |
| seq_along(), quantile() | row_number(), ntile(), min_ran() etc | |
| no easy way | complete(), expand() | often used with nesting(), see also full_seq() |
| expand.grid() | crossing() | |
| ifelse(is.na(...), ...) | drop_na(), replace_na() | see also fill(), coalesce() |
| some mix of paste/strsplit | separate(), unite() | |
| reshape2::dcast() | spread() | |
| reshape2::melt() | gather() | |
| replicate() | rerun() | |
| unlist(lapply(x, `[[`, n)) | pluck() | |
| lapply(), sapply() | map(), map2() | see also map_chr(), map_lgl(), map_int(), map_dbl(), map_df() |
| paste0() | glue() | |
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment