Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 4

Karuppasamy M Bsc-IT(shift-2) 22107096

R PROGRAMMING
Assignment - 1

#programs

assignment <- function() {


my_function <- function() {
print("Hello World!")
}
my_function()

#defaut value to parameters


my_function <- function(country = "Norway") {
paste("I am from", country)
}
my_function("Sweden")
my_function("India")
my_function() # will get the default value, which is Norway
my_function("USA")

#nested functions
Nested_function <- function(x, y) {
a <- x + y
return(a)
}
Nested_function(Nested_function(2,2), Nested_function(3,3))

#another nested function


Outer_func <- function(x) {
Inner_func <- function(y) {
a <- x + y
return(a)
Karuppasamy M Bsc-IT(shift-2) 22107096

}
return (Inner_func)
}
output <- Outer_func(3) # To call the Outer_func
output(5)

#using global variable in function


txt <- "global variable"
my_function <- function() {
txt = "fantastic"
paste("R is", txt)
}
my_function()

txt
my_function <- function() {
txt <<- "fantastic"
paste("R is", txt)
}
my_function()
print(txt)

txt <- "awesome"


my_function <- function() {
txt <<- "fantastic"
paste("R is", txt)
}
my_function()
paste("R is", txt)
Karuppasamy M Bsc-IT(shift-2) 22107096

#Math Functions
# Functions for basic arithmetic operations
add <- function(x, y) {
return(x + y)
}

subtract <- function(x, y) {


return(x - y)
}

multiply <- function(x, y) {


return(x * y)
}

divide <- function(x, y) {


return(x / y)
}

num1 <- as.numeric(readline(prompt="Enter first number: "))


num2 <- as.numeric(readline(prompt="Enter second number: "))
operation <- readline(prompt="Enter operation (+, -, *, /): ")

result <- switch(operation,


"+" = add(num1, num2),
"-" = subtract(num1, num2),
"*" = multiply(num1, num2),
"/" = divide(num1, num2),
"Invalid operation")
cat("The result is:", result)
Karuppasamy M Bsc-IT(shift-2) 22107096

math_function <- function(){


x=10
y=4
z = 7.9

abs(x)
sqrt(y)
log(x)
log10(x)
round(z, 2)
floor(z)
ceiling(z)
exp(x)
}
math_function()

String_function <- function() {


x ="string manuplation"

nchar(x)
paste(x, sep="")
strsplit(x, " ")
substr(x, 3, 18)
tolower(x)
toupper(x)
trimws(x)
}

String_function()
}
assignment()

You might also like