create function in r code example

Example 1: fuction in r

# Create a function to print squares of numbers in sequence.
new.function <- function(a) {
   for(i in 1:a) {
      b <- i^2
      print(b)
   }
}

# Call the function new.function supplying 6 as an argument.
new.function(6)

Example 2: custom function in r

# create custom function 

addition <- function(x) { 
y <- x + 1			
print(y) 

} 


z <- 2
addition(z)  # call new function on variable, z
> 3    # R returns the new value created by function

Example 3: R sample() funciton in python

import numpy as np
np.random.choice(values, size=1000,  replace=True, p=probability)

# values is the input values that correspond to the weights
# size is the number of samples to generate
# Replace specifies if it's with or without replacement
# p is the probability of choosing each corresponding value in values

Example 4: vars() in R

vars() in R: vars() is a quoting function that takes inputs to be evaluated in the context of a dataset. These inputs can be: variable names. complex expressions.