Wednesday, 25 October 2017

SQL in R - I

SQL was invented in the 1970s. Over the years, it has become quite popular among developers interacting with databases for its power while at the same time offering ease of use abilities. Though initially SQL was confined to the realm of databases, it has slowly and steadily pervaded various technologies. Examples of  SQL usage are seen in below cases to name a few:

a) HiveQL

b) Spark SQL

c) Google BigQuery

d) Apache Drill

It is, therefore, not surprising that R does not lag behind  and also supports SQL via sqldf package. So, let's explore how SQL can be used in R.

Details of sqldf package gives a fair idea about the manner in which SQL can be used to query dataframes in R. The first step is, of course, to install the sqldf package itself in R Studio as shown below:


Click on Install text under Packages tab in R Studio. This will bring up the Install Packages dialog in which we enter sqldf as shown below:


















Once we select sqldf from the prompted values, click on Install button. Once the installation of the package is complete, we can see that the following commands run on the console.







Then, we load the sqldf package using library command as shown below to use this package.









Running data() command shows all the default datasets available in R environment.

























We will use these default datasets to play with SQL in R. First, let us prepare a dataframe based on precip dataset as shown below:

> precip_data <- data.frame(attr(precip,"names"),precip)
> colnames(precip_data) <- c("Cities","Precipitation")
> head(precip_data)

       Cities Precipitation
1      Mobile          67.0
2      Juneau          54.7
3     Phoenix           7.0
4 Little Rock          48.5
5 Los Angeles          14.0
6  Sacramento          17.2

A quick look at the structure of this dataframe shows that the dataframe has two columns: one consisting of factors and the other numeric.

> str(precip_data)
'data.frame':    70 obs. of  2 variables:
 $ Cities       : Factor w/ 69 levels "Albany","Albuquerque",..: 42 33 51 35 36 58 60 21 27 69 ...
 $ Precipitation: num  67 54.7 7 48.5 14 17.2 20.7 13 43.4 40.2 ...
> 

We can a simple select on the dataframe as shown below to see the complete data:

> sqldf("select * from precip_data")
                Cities Precipitation
1               Mobile          67.0
2               Juneau          54.7
3              Phoenix           7.0
4          Little Rock          48.5
5          Los Angeles          14.0
6           Sacramento          17.2
7        San Francisco          20.7
8               Denver          13.0
9             Hartford          43.4
10          Wilmington          40.2
11          Washington          38.9
12        Jacksonville          54.5
13               Miami          59.8
14             Atlanta          48.3
15            Honolulu          22.9
16               Boise          11.5
17             Chicago          34.4
18              Peoria          35.1
19        Indianapolis          38.7
20          Des Moines          30.8
21             Wichita          30.6
22          Louisville          43.1
23         New Orleans          56.8
24            Portland          40.8
25           Baltimore          41.8
26              Boston          42.5
27             Detroit          31.0
28    Sault Ste. Marie          31.7
29              Duluth          30.2
30 Minneapolis/St Paul          25.9
31             Jackson          49.2
32         Kansas City          37.0
33            St Louis          35.9
34         Great Falls          15.0
35               Omaha          30.2
36                Reno           7.2
37             Concord          36.2
38       Atlantic City          45.5
39         Albuquerque           7.8
40              Albany          33.4
41             Buffalo          36.1
42            New York          40.2
43           Charlotte          42.7
44             Raleigh          42.5
45             Bismark          16.2
46          Cincinnati          39.0
47           Cleveland          35.0
48            Columbus          37.0
49       Oklahoma City          31.4
50            Portland          37.6
51        Philadelphia          39.9
52           Pittsburg          36.2
53          Providence          42.8
54            Columbia          46.4
55         Sioux Falls          24.7
56             Memphis          49.1
57           Nashville          46.0
58              Dallas          35.9
59             El Paso           7.8
60             Houston          48.2
61      Salt Lake City          15.2
62          Burlington          32.5
63             Norfolk          44.7
64            Richmond          42.6
65      Seattle Tacoma          38.8
66             Spokane          17.4
67          Charleston          40.8
68           Milwaukee          29.1
69            Cheyenne          14.6
70            San Juan          59.2

In order to select just one column, we can rewrite the SQL to as shown below:

> sqldf("select cities from precip_data")
                Cities
1               Mobile
2               Juneau
3              Phoenix
4          Little Rock
5          Los Angeles
6           Sacramento
7        San Francisco
8               Denver
9             Hartford
10          Wilmington
11          Washington
12        Jacksonville
13               Miami
14             Atlanta
15            Honolulu
16               Boise
17             Chicago
18              Peoria
19        Indianapolis
20          Des Moines
21             Wichita
22          Louisville
23         New Orleans
24            Portland
25           Baltimore
26              Boston
27             Detroit
28    Sault Ste. Marie
29              Duluth
30 Minneapolis/St Paul
31             Jackson
32         Kansas City
33            St Louis
34         Great Falls
35               Omaha
36                Reno
37             Concord
38       Atlantic City
39         Albuquerque
40              Albany
41             Buffalo
42            New York
43           Charlotte
44             Raleigh
45             Bismark
46          Cincinnati
47           Cleveland
48            Columbus
49       Oklahoma City
50            Portland
51        Philadelphia
52           Pittsburg
53          Providence
54            Columbia
55         Sioux Falls
56             Memphis
57           Nashville
58              Dallas
59             El Paso
60             Houston
61      Salt Lake City
62          Burlington
63             Norfolk
64            Richmond
65      Seattle Tacoma
66             Spokane
67          Charleston
68           Milwaukee
69            Cheyenne
70            San Juan

To limit the number of rows in the returned dataset, limit can be used as shown below:

> sqldf("select * from precip_data limit 5")
       Cities Precipitation
1      Mobile          67.0
2      Juneau          54.7
3     Phoenix           7.0
4 Little Rock          48.5
5 Los Angeles          14.0

Two forms of column alias are show below.

> sqldf("select cities as USCities from precip_data limit 5")
     USCities
1      Mobile
2      Juneau
3     Phoenix
4 Little Rock
5 Los Angeles

> sqldf("select cities 'US Cities' from precip_data limit 5")
    US Cities
1      Mobile
2      Juneau
3     Phoenix
4 Little Rock
5 Los Angeles
>

Calculations are allowed on columns containing numeric values. So, a query like the one below is entirely plausible:

> sqldf("select cities,precipitation*2 from precip_data limit 5")
       Cities precipitation*2
1      Mobile           134.0
2      Juneau           109.4
3     Phoenix            14.0
4 Little Rock            97.0
5 Los Angeles            28.0

To return limited rows based on a search criterion, we can use the where clause as shown below:

> sqldf("select cities,precipitation from precip_data where cities like 'New%'")
       Cities Precipitation
1 New Orleans          56.8
2    New York          40.2

The next query uses a string function, instr to return the same results as shown below:

> sqldf("select cities,precipitation from precip_data where instr(cities,'New')")
       Cities Precipitation
1 New Orleans          56.8
2    New York          40.2

We can put a where clause on the numeric column as shown below:

 > sqldf("select cities,precipitation from precip_data where precipitation >= 50")
        Cities Precipitation
1       Mobile          67.0
2       Juneau          54.7
3 Jacksonville          54.5
4        Miami          59.8
5  New Orleans          56.8
6     San Juan          59.2

Usage of between is shown in the below query:

> sqldf("select cities,precipitation from precip_data where precipitation between 55 and 60")
       Cities Precipitation
1       Miami          59.8
2 New Orleans          56.8
3    San Juan          59.2

For discontinuous values, we can use in as shown below:

> sqldf("select cities,precipitation from precip_data where precipitation in (30.2,35.9)")
    Cities Precipitation
1   Duluth          30.2
2 St Louis          35.9
3    Omaha          30.2
4   Dallas          35.9

Now, let us use mtcars dataframe to see the other features of SQL in R.

> str(mtcars)
'data.frame':    32 obs. of  11 variables:
 $ mpg : num  21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
 $ cyl : num  6 6 4 6 8 6 8 4 4 6 ...
 $ disp: num  160 160 108 258 360 ...
 $ hp  : num  110 110 93 110 175 105 245 62 95 123 ...
 $ drat: num  3.9 3.9 3.85 3.08 3.15 2.76 3.21 3.69 3.92 3.92 ...
 $ wt  : num  2.62 2.88 2.32 3.21 3.44 ...
 $ qsec: num  16.5 17 18.6 19.4 17 ...
 $ vs  : num  0 0 1 1 0 1 0 1 1 1 ...
 $ am  : num  1 1 1 0 0 0 0 0 0 0 ...
 $ gear: num  4 4 4 3 3 3 3 4 4 4 ...
 $ carb: num  4 4 1 1 2 1 4 2 2 4 ...

To find out unique values, we can use distinct as shown below:

> sqldf("select distinct am from mtcars")
  am
1  1
2  0

Support for aggregate functions and nesting of functions are shown below:

> sqldf("select count(*) from mtcars")
  count(*)
1       32

> sqldf("select count(am) from mtcars")
  count(am)
1        32

> sqldf("select count(distinct am) from mtcars")
  count(distinct am)
1                  2

count(*) returns the number of rows.

max() gives the maximum, min() gives the minimum, round() rounds the numeric value, and sum() calculates the sum of the values. These are shown below:

> sqldf("select min(disp), max(disp) from mtcars")
  min(disp) max(disp)
1      71.1       472
>
> sqldf("select round(min(disp)), round(max(disp)) from mtcars")
  round(min(disp)) round(max(disp))
1               71              472
>
> sqldf("select sum(wt) from mtcars")
  sum(wt)
1 102.952

The rest of the SQL in R discussion is carried out in Part II ...

Thursday, 28 September 2017

Set Operations in R

After a fairly long break, we are back to writing interesting insights on data and related areas. The focus of this short post is on the set operations in R. Set operations are useful when we have to find out, say, common elements between two sets of data or need the elements of one set of data not present in another set of data. We will consider a few functions in R that can be of immense help in data analysis.

To illustrate the functions, we use two sets of vectors called p and q defined as follows:









Unique() function gives the unique elements in a vector. Let us use this function on p and q to fetch the unique elements as shown below:







As can be seen, unique function on p and q results in distinct elements and duplicates are discarded. To get the union of elements in p and q, we use the union function as below:






Note that the union of p and q results in distinct elements from p and q. Next, we look at intersect function that returns in common elements between the two sets under consideration.







setdiff function returns the elements of the first set not present in the second set. setdiff is like minus operation in a relational database. Unlike union or intersect where the order of the dataset does not matter, in the case of setdiff, it matters.







Note again that the setdiff returns only distinct elements.

We can create a custom setdiff function that returns duplicates as shown below:






To see if two vectors are identical we can use setequal as shown below:







setequal returns false in the first case as p and q are not equal and true in the second case as p is same as p.

is.element returns TRUE or FALSE based on whether the element in the first dataset is present in the second dataset or not. It is same as %in%  operator. The is.element is shown below:






The last function we discuss is choose. choose(n,r) is the same as nCr defined in Combinatorics. choose returns the binomial coefficient. In other words, choose(n,r) returns the number of possible subsets of size r chosen from n elements. Examples are shown below:











Friday, 23 June 2017

Statistical Functions in Excel I


In the first post of Statistical Functions in Excel, we will cover a part of the functions that can be used for statistical analysis available in Excel. While there are several functions with a variety of functionality, we will focus on Statistical functions only in this post. It is assumed that the reader will know basics of Statistics and Like before, we will explore these functions in Excel 2016.


Let's take a quick look at some of these functions that are available OOTB on the Status Bar.












If we enter 1 to 4 in cells as shown above and select them, then, we see the Average, Count and Sum shown on the Status Bar on the right bottom of the window. We can customize the measures shown in the Status Bar by right clicking anywhere on the Status Bar and, then, clicking Numerical Count, Minimum and Maximum from the Menu Items shown. This is shown below:




















If we wish to add any more functions, then, we can add the functions in the Status Bar using VBA. But, that is a story for another day. Continuing with the above Menu Items figure, we see above that Average, Count, and Sum are checked. So, we see them in the Status Bar once we select cells containing numbers. Once we click Numerical Count, Minimum and Maximum, we see a tick against these measures as shown below:




















To confirm that these measures appear on the Status Bar, we can select cells as shown below and see that the corresponding measures are shown:












Count gives the count of all cells selected while Numerical Count gives the count of all cells containing numbers only. Min and Max give the minimum and maximum of the selected numbers. Now, that we have seen the OOTB functionality, let us quickly see the Statistical functions in alphabetical order:

AVEDEV: Calculates the average of the absolute deviations of data points from their mean. Mathematically, it can be written as shown below where x is a It can take numbers in the form of arguments, but not exceeding 255 in count, like, AVEDEV(1,2,3,4) that will return 1. If more than 255 arguments are passed, then, we get below error:









A work around is to use enter these values in cells and use cell range like, AVEDEV(A1:A2000). This is applicable to many of the statistical functions that we shall see shortly.

AVERAGE: Calculates the average. We can select cells and, then, insert numbers as shown below:



The result of the function is 2.5 and that compares well with the value in the Status bar as shown below:














AVERAGEA: Calculates the average like the AVERAGE function, but with a twist. While AVERAGE ignores any text, AVERAGEA counts any text as a member contributing zero to the sum. This is clearly seen below where for the selection below, AVERAGE returns 2.5 and AVERAGEA returns 2.222222222.









For the selection below, AVERAGE function returns the same value 2.5 whereas AVERAGEA returns a different value because boolean values are treated as numbers by AVERAGEA. TRUE is treated as 1 and FALSE as 0.








AVERAGEIF: Calculates the average of contents in a range of cells based on some criteria. Example is shown below:













Only those value that qualify the condition that value is not equal to 2 or 3.

AVERAGEIFS: Similar to above function. But, we can give multiple criteria. Example is shown below:











CORREL: Calculates the correlation of two arrays containing the same number of elements. Example is show below:













COUNT: Calculates the number of cells having numbers only. See example below:














COUNTA: Calculates the number of cells having any content. See example below:














The reason COUNTA returns 5 is because cell E4 has a blank space.

COUNTBLANK: Calculates the number of blanks in the cells. See example below:















Following from the last example, result is 1 because cell E4 has a blank space.

COUNTIF: Calculates the number of cells having a content based on a condition like we saw in the case of AVERAGEIF. See example below:














The number of cells containing FOO is counted here.

COUNTIFS: Similar to COUNTIF, but based on more than one condition like AVERAGEIFS.

COVARIANCE.P: Calculates the covariance of a population. See example below:











COVARIANCE.P: Calculates the covariance of a sample. See example below:











DEVSQ: Calculates the sum of the squares of the deviations from the average  See example below:













FORECAST, FORECAST.ETS, FORECAST.ETS.CONFINT, FORECAST.ETS.SEASONALITY, FORECAST.ETS.STAT, and FORECAST.LINEAR are functions that can be used for prediction analysis where future data can be predicted based on historical values.

FREQUENCY: is a wonderful function that can be used to classify raw data into bins. As an example, see below numbers where numbers 1 to 9 and they are classified to 4 bins:

less than 3;
between 3 and 6;
between 6 and 9;
greater than 9;



















Enter the formula as shown below:


















On pressing Enter, the function returns 3 that is in the first bin (less than 3). To get the number of elements in the other bins, after selecting the cell containing the function, drag the selection down such that the selection equals the number of bin. Here, since there are 4 bins, we select 3 cells below the cell containing the function as shown below:


















Once this is done, then, click on F2 and, then, CTRL+Shift+Enter. This will populate the selected cells with the number of elements as shown below:


















GEOMEAN: Calculates the geometric mean of an array of numbers. See example below:











GROWTH: Predicts a value based on the assumption that the growth is exponential.

HARMEAN: Calculates the harmonic mean of an array of numbers. See example below:











INTERCEPT: Calculates the point at which a line will intersect the y-axis when given existing y values and x values. See example below:












KURT: Calculates the kurtosis of an array. See example below:
















LINEST: is a line fitting function and calculates the best straight line.

LOGEST: is a curve fitting function and calculates the best exponential curve.

MAX: Calculates the maximum value from an array of numbers. See example below:














MAXA: Calculates the maximum value from any array of numbers, strings and boolean values.

MAXIFS: Calculates the maximum value in an array of numbers based on a criteria.

MEDIAN: Calculates the median of an array of numbers. See example below:















The rest of the functions will be covered in a following post.