Last updated: 2023-10-08

Checks: 7 0

Knit directory: Pandas-30-R/

This reproducible R Markdown analysis was created with workflowr (version 1.7.0). The Checks tab describes the reproducibility checks that were applied when the results were created. The Past versions tab lists the development history.


Great! Since the R Markdown file has been committed to the Git repository, you know the exact version of the code that produced these results.

Great job! The global environment was empty. Objects defined in the global environment can affect the analysis in your R Markdown file in unknown ways. For reproduciblity it’s best to always run the code in an empty environment.

The command set.seed(20221023) was run prior to running the code in the R Markdown file. Setting a seed ensures that any results that rely on randomness, e.g. subsampling or permutations, are reproducible.

Great job! Recording the operating system, R version, and package versions is critical for reproducibility.

Nice! There were no cached chunks for this analysis, so you can be confident that you successfully produced the results during this run.

Great job! Using relative paths to the files within your workflowr project makes it easier to run your code on other machines.

Great! You are using Git for version control. Tracking code development and connecting the code version to the results is critical for reproducibility.

The results in this page were generated with repository version 066a00f. See the Past versions tab to see a history of the changes made to the R Markdown and HTML files.

Note that you need to be careful to ensure that all relevant files for the analysis have been committed to Git prior to generating the results (you can use wflow_publish or wflow_git_commit). workflowr only checks the R Markdown file, but you know if there are other scripts or data files that it depends on. Below is the status of the Git repository when the results were generated:


Ignored files:
    Ignored:    .Rhistory
    Ignored:    .Rproj.user/
    Ignored:    dev/
    Ignored:    renv/

Untracked files:
    Untracked:  mydatabase.db

Unstaged changes:
    Modified:   renv.lock

Note that any generated files, e.g. HTML, png, CSS, etc., are not included in this status report because it is ok for generated content to have uncommitted changes.


These are the previous versions of the repository in which changes were made to the R Markdown (analysis/method27-finding-the-distribution-of-values.Rmd) and HTML (docs/method27-finding-the-distribution-of-values.html) files. If you’ve configured a remote Git repository (see ?wflow_git_remote), click on the hyperlinks in the table below to view the files as they were in that past version.

File Version Author Date Message
html 253f970 Mena WANG 2023-09-24 Build site.
html 7139b81 Mena WANG 2023-09-18 Build site.
html 406fa10 Mena WANG 2023-09-10 Build site.
html e025247 Mena WANG 2023-09-03 Build site.
html 7f8aaeb Mena WANG 2023-08-15 Build site.
html be1850c Mena WANG 2023-08-15 Build site.
html f5a895a Mena WANG 2023-08-13 Build site.
html db3e0fe Mena WANG 2023-07-22 Build site.
html 7aa3195 Mena WANG 2023-07-22 Build site.
html 0db3ba4 Mena WANG 2023-02-26 Build site.
html e3221e5 Mena WANG 2022-12-13 Build site.
html 2522fc8 Mena WANG 2022-12-10 Build site.
html b06fbb1 Mena WANG 2022-12-02 Build site.
Rmd 5e3738a Mena WANG 2022-12-02 add method28-29
html a20b54f Mena WANG 2022-11-29 Build site.
Rmd 364f0c3 Mena WANG 2022-11-29 add method27
html 5d4a24a Mena WANG 2022-11-29 Build site.
Rmd a65e3ef Mena WANG 2022-11-29 add method27

Introduction

Provide a Python to R translation of 30 essential Pandas methods introduced by Avi Chawla in The Only 30 Methods You Should Master To Become A Pandas Pro published on TowardsDataScience.

Set up

# enable python in RMarkdown
library(reticulate)

Create the dataframe in Python

import pandas as pd

df = pd.DataFrame([[1, 'A'], 
                   [2, 'B'], 
                   [1, 'A']], 
                  columns = ["col1", "col2"])

print(df)
   col1 col2
0     1    A
1     2    B
2     1    A

Load the dataframe into R

df <- py$df #access df as saved in Python(py) above

print(df)
  col1 col2
1    1    A
2    2    B
3    1    A

Method #27 Finding the Distribution of Values

Python

In Python, we can use value_counts() to find frequency of each unique values, and use sort to keep the most frequently appeared value at the top.

df["col2"].value_counts(sort = True)
A    2
B    1
Name: col2, dtype: int64

We can get a percentage instead of value counts by adding the normalize = True argument.

df["col2"].value_counts(sort = True, normalize = True)\
          .round(3) * 100 # round it up if you like
A    66.7
B    33.3
Name: col2, dtype: float64

R

In R, this is easy to do with count()

library(dplyr)

df |> count(col2, sort = TRUE)
  col2 n
1    A 2
2    B 1

To add percentage takes a bit more code, but you can have a nice table with both the counts and percentage in it together.

df |> 
  group_by(col2) |> 
  summarize(n = n()) |> # get counts
  mutate(pct = n / sum(n) * 100) |> # get percentage
  arrange(n |> desc()) # sort descending
# A tibble: 2 × 3
  col2      n   pct
  <chr> <int> <dbl>
1 A         2  66.7
2 B         1  33.3

We could also use tabyl() in the janitor package to do it in one line.

library(janitor)

df |> tabyl(col2)
 col2 n   percent
    A 2 0.6666667
    B 1 0.3333333

Bonus: Advanced frequency tables

R

tabyl has much advanced functionalities that would allow us to create customized frequency tables. Please see below two simple examples and much more available here

humans <- starwars |> filter(species == "Human")

# one-way table
humans |> 
  tabyl(eye_color) |> 
  adorn_totals() |> 
  adorn_pct_formatting(digits = 1)  # format the percentage
 eye_color  n percent
      blue 12   34.3%
 blue-gray  1    2.9%
     brown 17   48.6%
      dark  1    2.9%
     hazel  2    5.7%
    yellow  2    5.7%
     Total 35  100.0%
# two-way table
humans |> 
  tabyl(eye_color,gender) |> 
  adorn_totals(c('row','col')) |> # add  total for both rows and columns
  adorn_percentages("all") |> # pct among all for each cell
  adorn_pct_formatting(digits = 1)  |> 
  adorn_ns() # add counts 
 eye_color  feminine  masculine       Total
      blue  8.6% (3) 25.7%  (9)  34.3% (12)
 blue-gray  0.0% (0)  2.9%  (1)   2.9%  (1)
     brown 14.3% (5) 34.3% (12)  48.6% (17)
      dark  0.0% (0)  2.9%  (1)   2.9%  (1)
     hazel  2.9% (1)  2.9%  (1)   5.7%  (2)
    yellow  0.0% (0)  5.7%  (2)   5.7%  (2)
     Total 25.7% (9) 74.3% (26) 100.0% (35)

Python

In Python, we could use sidetable to create customized frequency tables. Follows please see some simple examples, and more is available here.

import sidetable 

humans = r.humans # take the dataset from R

humans.stb.freq(['eye_color']) # one category
   eye_color  count    percent  cumulative_count  cumulative_percent
0      brown     17  48.571429                17           48.571429
1       blue     12  34.285714                29           82.857143
2     yellow      2   5.714286                31           88.571429
3      hazel      2   5.714286                33           94.285714
4       dark      1   2.857143                34           97.142857
5  blue-gray      1   2.857143                35          100.000000

When it comes to two categories. I prefer tabyl output above to the sidetable version below. For me personally, it is easier to interpret when the values of the two categories are represented in the columns and rows respectively. In Python, we can use the crosstab function to do this, please refer to method #29 in this series later.

humans.stb.freq(['gender','eye_color']) # two categories
      gender  eye_color  count    percent  cumulative_count  cumulative_percent
0  masculine      brown     12  34.285714                12           34.285714
1  masculine       blue      9  25.714286                21           60.000000
2   feminine      brown      5  14.285714                26           74.285714
3   feminine       blue      3   8.571429                29           82.857143
4  masculine     yellow      2   5.714286                31           88.571429
5  masculine      hazel      1   2.857143                32           91.428571
6  masculine       dark      1   2.857143                33           94.285714
7  masculine  blue-gray      1   2.857143                34           97.142857
8   feminine      hazel      1   2.857143                35          100.000000

sessionInfo()
R version 4.2.1 (2022-06-23 ucrt)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 19045)

Matrix products: default

locale:
[1] LC_COLLATE=English_Australia.utf8  LC_CTYPE=English_Australia.utf8   
[3] LC_MONETARY=English_Australia.utf8 LC_NUMERIC=C                      
[5] LC_TIME=English_Australia.utf8    

attached base packages:
[1] stats     graphics  grDevices datasets  utils     methods   base     

other attached packages:
[1] janitor_2.2.0   dplyr_1.1.2     reticulate_1.30

loaded via a namespace (and not attached):
 [1] Rcpp_1.0.11       pillar_1.9.0      compiler_4.2.1    bslib_0.5.0      
 [5] later_1.3.1       jquerylib_0.1.4   git2r_0.32.0      workflowr_1.7.0  
 [9] tools_4.2.1       digest_0.6.33     timechange_0.2.0  lubridate_1.9.2  
[13] lattice_0.20-45   jsonlite_1.8.7    evaluate_0.21     lifecycle_1.0.3  
[17] tibble_3.2.1      png_0.1-8         pkgconfig_2.0.3   rlang_1.1.1      
[21] Matrix_1.4-1      cli_3.6.1         rstudioapi_0.15.0 yaml_2.3.7       
[25] xfun_0.39         fastmap_1.1.1     withr_2.5.0       stringr_1.5.0    
[29] knitr_1.43        generics_0.1.3    fs_1.6.2          vctrs_0.6.3      
[33] sass_0.4.7        tidyselect_1.2.0  grid_4.2.1        rprojroot_2.0.3  
[37] snakecase_0.11.0  here_1.0.1        glue_1.6.2        R6_2.5.1         
[41] fansi_1.0.4       rmarkdown_2.23    purrr_1.0.1       tidyr_1.3.0      
[45] magrittr_2.0.3    whisker_0.4.1     promises_1.2.0.1  htmltools_0.5.5  
[49] renv_1.0.0        httpuv_1.6.11     utf8_1.2.3        stringi_1.7.12   
[53] cachem_1.0.8