Feb
23

Vector calculation in python and in R

There are different ways doing math for vector in python

1. use loop

# Create a vector,which begin with 0 to 10, and 200 different elements
x = numpy. linspace(0,10,200)

# Turn numpyarray to list
x = list(x)

for member in x:
y.append(math.sin(member))

2. use loop, but in list

# Method 2: use loop but in list
y=[math.sin(member) for member in x ]

3. use numpy

# Method 3: use numpy
x = np.array(x)
y = np.sin(x)

4. use map and lambda functions

# Method 4: use map and lambda functions
map(lambda member: math.sin(member), x)

In R language, the vector math is relative easy

> a <- seq(1,10, length.out=200)
> b <- sin(a)

Alternative for creating the vector “a”

> a <- seq(1,10, 0.1)
> a <- seq(1,10,by = 0.1)

Written by connygy. Posted in python, R

Tags: , ,

Trackback from your site.

Leave a comment