Using R in Jupyter notebooks.

-- see the file on Using Python in Jupyter for some basics on Jupyter. This file is only about the R language.

R knows about integers, floating point numbers, even complex numbers like 1+2i.


In [1]:
2+2


4

In [2]:
sin(.1)


0.0998334166468282

In [6]:
1i*1i


-1+0i

In [9]:
(1+2i)*(2+3i)


-4+7i

A vector is a concatenation of numbers, so use the c operator for form the vector.

A variable can be assigned using either the equals sign, or the assignment arrow.


In [14]:
x <- c(10.4, 5.6, 3.1, 6.4, 21.7)

In [11]:
x


  1. 10.4
  2. 5.6
  3. 3.1
  4. 6.4
  5. 21.7

In [15]:
y = c(x,2,2,x)

In [16]:
y


  1. 10.4
  2. 5.6
  3. 3.1
  4. 6.4
  5. 21.7
  6. 2
  7. 2
  8. 10.4
  9. 5.6
  10. 3.1
  11. 6.4
  12. 21.7

R has a funny way of adding vectors of different lengths. It just recycles the entries from the shorter vector.


In [18]:
x+y


Warning message in x + y:
“longer object length is not a multiple of shorter object length”
  1. 20.8
  2. 11.2
  3. 6.2
  4. 12.8
  5. 43.4
  6. 12.4
  7. 7.6
  8. 13.5
  9. 12
  10. 24.8
  11. 16.8
  12. 27.3

In [19]:
1/x


  1. 0.0961538461538461
  2. 0.178571428571429
  3. 0.32258064516129
  4. 0.15625
  5. 0.0460829493087558

In [20]:
y/x


Warning message in y/x:
“longer object length is not a multiple of shorter object length”
  1. 1
  2. 1
  3. 1
  4. 1
  5. 1
  6. 0.192307692307692
  7. 0.357142857142857
  8. 3.35483870967742
  9. 0.875
  10. 0.142857142857143
  11. 0.615384615384615
  12. 3.875

In [21]:
mean(x)


9.44

In [22]:
var(x)


53.853

In [23]:
# a direct way to compute the variance
sum((x-mean(x))^2)/(length(x)-1)


53.853

Matrices

Be careful with matrices. They are treated as lists of numbers, with a dimension attached.

The star operator does a entry-by-entry multiplication, which is NOT matrix multiplication.

For matrix multiplication, use

m %*% m

In [24]:
m = array(c(1,2,3,4),dim=c(2,2))

In [25]:
m


13
24

In [26]:
det(m)


-2

In [27]:
m*m


1 9
4 16

In [28]:
m%*%m


715
1022

In [29]:
m^2


1 9
4 16

Plotting


In [31]:
plot(c(1,2,3,4))



In [32]:
# Define 2 vectors
cars <- c(1, 3, 6, 4, 9)
trucks <- c(2, 5, 4, 5, 12)

# Graph cars using a y axis that ranges from 0 to 12
plot(cars, type="o", col="blue", ylim=c(0,12))

# Graph trucks with red dashed line and square points
lines(trucks, type="o", pch=22, lty=2, col="red")

# Create a title with a red, bold/italic font
title(main="Autos", col.main="red", font.main=4)


Going further

Here is a good reference to the R language, which I've just been following along as I learn it in Jupyter.

An Introduction to R


In [ ]: