Self-defined Functions

R

In R, a function can be defined using function and braces are necessary to enclose the function body.

square = function(x){
  return(x ** 2)
}

square(10)
## [1] 100

Python

In python, a function can be defined using def, and the body is recognised through the indentations. Four spaces is commonly used for the indentation.

def square(x):
    new_value = x ** 2
    return new_value
    
square(10)
## 100

List comprehensions

Generation of special lists/vectors is a common task in any programming language.

R

x = 1:20
(2*x)[x %% 2 == 0]
##  [1]  4  8 12 16 20 24 28 32 36 40
ifelse(x %% 2 == 0, 2*x, 0)
##  [1]  0  4  0  8  0 12  0 16  0 20  0 24  0 28  0 32  0 36  0 40

Python

In python, list comprehensions is a powerful way to generate a list in the coding style of a for loop.

[2*x for x in range(1, 21) if x % 2 == 0]
## [4, 8, 12, 16, 20, 24, 28, 32, 36, 40]
[2*x if x % 2 == 0 else 0 for x in range(1, 21)]
## [0, 4, 0, 8, 0, 12, 0, 16, 0, 20, 0, 24, 0, 28, 0, 32, 0, 36, 0, 40]

Error handling

Mapping

R

x = 1:10
purrr::map_dbl(x, ~.x^2)
##  [1]   1   4   9  16  25  36  49  64  81 100

Python

In python, list comprehensions is a powerful way to generate a list in the coding style of a for loop.

x = list(range(1, 11))
list(map(lambda num: num**2, x))
## [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]