NumPy For R
NumPy For R
Help
R/S-Plus Python Description
help.start() help() Browse help interactively
help() help Help on using help
help(plot) or ?plot help(plot) or ?plot Help for a function
help(package='splines') help(pylab) Help for a toolbox/library
package
demo() Demonstration examples
example(plot) Example using a function
Using interactively
R/S-Plus Python Description
Rgui ipython -pylab Start session
TAB Auto completion
source('foo.R') execfile('foo.py') or run Run code from file
foo.py
history() hist -n Command history
savehistory(file=".Rhistory") Save command history
q(save='no') CTRL-D End session
CTRL-Z # windows
sys.exit()
Operators
R/S-Plus Python Description
help(Syntax) Help on operator syntax
Arithmetic operators
R/S-Plus Python Description
a<-1; b<-2 a=1; b=1 Assignment; defining a
number
a + b a + b or add(a,b) Addition
a - b a - b or subtract(a,b) Subtraction
a * b a * b or multiply(a,b) Multiplication
a / b a / b or divide(a,b) Division
a ^ b a ** b Power, $a^b$
power(a,b)
pow(a,b)
a %% b a % b Remainder
remainder(a,b)
fmod(a,b)
a %/% b Integer division
a+=b or add(a,b,a) In place operation to save
array creation overhead
factorial(a) Factorial, $n!$
Relational operators
R/S-Plus Python Description
a == b a == b or equal(a,b) Equal
a < b a < b or less(a,b) Less than
a > b a > b or greater(a,b) Greater than
a <= b a <= b or less_equal(a,b) Less than or equal
a >= b a >= b or greater_equal(a,b) Greater than or equal
a != b a != b or not_equal(a,b) Not Equal
Logical operators
R/S-Plus Python Description
a && b a and b Short-circuit logical AND
a || b a or b Short-circuit logical OR
a & b logical_and(a,b) or a and b Element-wise logical AND
a | b logical_or(a,b) or a or b Element-wise logical OR
xor(a, b) logical_xor(a,b) Logical EXCLUSIVE OR
!a logical_not(a) or not a Logical NOT
Round off
R/S-Plus Python Description
round(a) around(a) or math.round(a) Round
ceil(a) ceil(a) Round up
floor(a) floor(a) Round down
fix(a) Round towards zero
Mathematical constants
R/S-Plus Python Description
pi math.pi $\pi=3.141592$
exp(1) math.e or math.exp(1) $e=2.718281$
Complex numbers
R/S-Plus Python Description
1i z = 1j Imaginary unit
z <- 3+4i z = 3+4j or z = A complex number, $3+4i$
complex(3,4)
abs(3+4i) or Mod(3+4i) abs(3+4j) Absolute value (modulus)
Re(3+4i) z.real Real part
Im(3+4i) z.imag Imaginary part
Arg(3+4i) Argument
Conj(3+4i) z.conj(); z.conjugate() Complex conjugate
Trigonometry
R/S-Plus Python Description
atan2(b,a) atan2(b,a) Arctangent, $\arctan(b/a)$
hypot(x,y) Hypotenus; Euclidean distance
Vectors
R/S-Plus Python Description
a <- c(2,3,4,5) a=array([2,3,4,5]) Row vector, $1 \times n$-
matrix
adash <- t(c(2,3,4,5)) array([2,3,4,5])[:,NewAxis] Column vector, $m \times
array([2,3,4,5]).reshape(-1,1)
r_[1:10,'c'] 1$-matrix
Sequences
R/S-Plus Python Description
seq(10) or 1:10 arange(1,11, dtype=Float) 1,2,3, ... ,10
range(1,11)
seq(0,length=10) arange(10.) 0.0,1.0,2.0, ... ,9.0
seq(1,10,by=3) arange(1,11,3) 1,4,7,10
seq(10,1) or 10:1 arange(10,0,-1) 10,9,8, ... ,1
seq(from=10,to=1,by=-3) arange(10,0,-3) 10,7,4,1
seq(1,10,length=7) linspace(1,10,7) Linearly spaced vector of
n=7 points
rev(a) a[::-1] or Reverse
a.fill(3), a[:] = 3 Set all values to same scalar
value
Concatenation (vectors)
R/S-Plus Python Description
c(a,a) concatenate((a,a)) Concatenate two vectors
c(1:4,a) concatenate((range(1,5),a),
axis=1)
Repeating
R/S-Plus Python Description
rep(a,times=2) concatenate((a,a)) 1 2 3, 1 2 3
rep(a,each=3) a.repeat(3) or 1 1 1, 2 2 2, 3 3 3
rep(a,a) a.repeat(a) or 1, 2 2, 3 3 3
Vector multiplication
R/S-Plus Python Description
a*a a*a Multiply two vectors
dot(u,v) Vector dot product, $u \cdot v$
Matrices
R/S-Plus Python Description
rbind(c(2,3),c(4,5)) a = array([[2,3],[4,5]]) Define a matrix
array(c(2,3,4,5), dim=c(2,2))
Array creation
R/S-Plus Python Description
matrix(0,3,5) or array(0,c(3,5)) zeros((3,5),Float) 0 filled array
zeros((3,5)) 0 filled array of integers
matrix(1,3,5) or array(1,c(3,5)) ones((3,5),Float) 1 filled array
matrix(9,3,5) or array(9,c(3,5)) Any number filled array
diag(1,3) identity(3) Identity matrix
diag(c(4,5,6)) diag((4,5,6)) Diagonal
a = empty((3,3)) Empty array
Assignment
R/S-Plus Python Description
a[,1] <- 99 a[:,0] = 99
a[,1] <- c(99,98,97) a[:,0] = array([99,98,97])
a[a>90] <- 90 (a>90).choose(a,90) Clipping: Replace all
a.clip(min=None, max=90)
elements over 90
a.clip(min=2, max=5) Clip upper and lower values
Sum
R/S-Plus Python Description
apply(a,2,sum) a.sum(axis=0) Sum of each column
apply(a,1,sum) a.sum(axis=1) Sum of each row
sum(a) a.sum() Sum of all elements
a.trace(offset=0) Sum along diagonal
apply(a,2,cumsum) a.cumsum(axis=0) Cumulative sum (columns)
Sorting
R/S-Plus Python Description
a = array([[4,3,2],[2,8,6], Example data
[1,4,7]])
t(sort(a)) a.ravel().sort() or Flat and sorted
apply(a,2,sort) a.sort(axis=0) or msort(a) Sort each column
t(apply(a,1,sort)) a.sort(axis=1) Sort each row
a[a[:,0].argsort(),] Sort rows (by first row)
order(a) a.ravel().argsort() Sort, return indices
a.argsort(axis=0) Sort each column,
return indices
a.argsort(axis=1) Sort each row, return
indices
Matrix manipulation
R/S-Plus Python Description
a[,4:1] fliplr(a) or a[:,::-1] Flip left-right
a[3:1,] flipud(a) or a[::-1,] Flip up-down
rot90(a) Rotate 90 degrees
kronecker(matrix(1,2,3),a) kron(ones((2,3)),a) Repeat matrix: [ a a a ; a a
a]
a[lower.tri(a)] <- 0 triu(a) Triangular, upper
a[upper.tri(a)] <- 0 tril(a) Triangular, lower
Equivalents to "size"
R/S-Plus Python Description
dim(a) a.shape or a.getshape() Matrix dimensions
ncol(a) a.shape[1] or size(a, axis=1) Number of columns
prod(dim(a)) a.size or size(a[, axis=None]) Number of elements
a.ndim Number of dimensions
object.size(a) a.nbytes Number of bytes used in
memory
Plotting
Log plots
R/S-Plus Python Description
plot(x,y, log="y") semilogy(a) logarithmic y-axis
plot(x,y, log="x") semilogx(a) logarithmic x-axis
plot(x,y, log="xy") loglog(a) logarithmic x and y axes
Functions
R/S-Plus Python Description
f <- function(x) sin(x/3) - Defining functions
cos(x/5)
plot(f, xlim=c(0,40), x = arrayrange(0,40,.5) Plot a function for given
type='p') y = sin(x/3) - cos(x/5)
plot(x,y, 'o') range
Polar plots
R/S-Plus Python Description
theta = arange(0,2*pi,0.001)
r = sin(2*theta)
polar(theta, rho)
Histogram plots
R/S-Plus Python Description
hist(rnorm(1000))
hist(rnorm(1000), breaks= -4:4)
hist(rnorm(1000), breaks=c(seq(-
5,0,0.25), seq(0.5,5,0.5)),
freq=F)
plot(apply(a,1,sort),type="l")
3d data
Data analysis
Statistics
R/S-Plus Python Description
apply(a,2,mean) a.mean(axis=0) Average
mean(a [,axis=0])
apply(a,2,median) median(a) or median(a [,axis=0]) Median
apply(a,2,sd) a.std(axis=0) or std(a [,axis=0]) Standard deviation
apply(a,2,var) a.var(axis=0) or var(a) Variance
cor(x,y) correlate(x,y) or corrcoef(x,y) Correlation coefficient
cov(x,y) cov(x,y) Covariance
Non-linear methods
Differential equations
R/S-Plus Python Description
diff(x, n=1, axis=0) Discrete difference function and
approximate derivative
Fourier analysis
R/S-Plus Python Description
fft(a) fft(a) or Fast fourier transform
fft(a, inverse=TRUE) ifft(a) or Inverse fourier transform
convolve(x,y) Linear convolution
Symbolic algebra; calculus
R/S-Plus Python Description
Programming
R/S-Plus Python Description
.R .py Script file extension
# # Comment symbol (rest of
line)
library(RSvgDevice) from pylab import * Import library functions
string <- "a <- 234" string="a=234" Eval
eval(parse(text=string)) eval(string)
Loops
R/S-Plus Python Description
for(i in 1:5) print(i) for i in range(1,6): for-statement
print(i)
for(i in 1:5) { for i in range(1,6): Multiline for statements
print(i) print(i)
print(i*2) print(i*2)
}
Conditionals
R/S-Plus Python Description
if (1>0) a <- 100 if 1>0: a=100 if-statement
ifelse(a>0,a,0) Ternary operator (if?true:false)
Debugging
R/S-Plus Python Description
.Last.value Most recent evaluated
expression
objects() List variables loaded into
memory
rm(x) Clear variable $x$ from
memory
print(a) print a Print