1. Introduction to R programming Element

Sahil Sahani
0

 


1. Introduction to R programming Element


1A) write an R program to implement expression assignment and decision making.

# Expression assignment
a <- 10
b <- 5

# Decision-making
if (a > b) {
  result <- "a is greater than b"
} else {
  result <- "b is greater than or equal to a"
}

# Print the result
cat("Result:", result, "\n")

    

OUTPUT :

[1] "b is greater than a"
    

1B) write an R program to design and implement loops.

#for loop to count numbers from a given range 
for (val in 1:5)
{
    #statement
    print(val)
}
#while loop to increase numbers in R
val<-1
while (val <=5)
{
    print(val)
    val=val+1
    
}
week<-c('sunday','monday','tuesday','thursday','friday','saturday')
for (day in week)
{
    print(day)
}

OUTPUT :

[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] "sunday"
[1] "monday"
[1] "tuesday"
[1] "thursday"
[1] "friday"
[1] "saturday"
    

1C) write an R program to demonstrate the use of essential data structures in R [Hint : vector,matrix,arrays].

# Vector
numeric_vector <- c(1, 2, 3, 4, 5)
character_vector <- c("apple", "banana", "orange")
logical_vector <- c(TRUE, FALSE, TRUE)

# Matrix
matrix_data <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 2, ncol = 3, byrow = TRUE)
rownames(matrix_data) <- c("Row1", "Row2")
colnames(matrix_data) <- c("Col1", "Col2", "Col3")

# Array
array_data <- array(1:24, dim = c(2, 3, 4))
dimnames(array_data) <- list(c("Row1", "Row2"), c("Col1", "Col2", "Col3"), c("Depth1", "Depth2", "Depth3", "Depth4"))

# Displaying the data structures
cat("Numeric Vector:\n", numeric_vector, "\n\n")
cat("Character Vector:\n", character_vector, "\n\n")
cat("Logical Vector:\n", logical_vector, "\n\n")

cat("Matrix:\n")
print(matrix_data)
cat("\n")

cat("Array:\n")
print(array_data)

OUTPUT :

Numeric Vector:
 1 2 3 4 5 
 Character Vector:
 apple banana orange 

Logical Vector:
 TRUE FALSE TRUE 

Matrix:
     Col1 Col2 Col3
Row1    1    2    3
Row2    4    5    6

Array:
, , Depth1

     Col1 Col2 Col3
Row1    1    3    5
Row2    2    4    6

, , Depth2

    Col1 Col2 Col3
Row1    7    9   11
Row2    8   10   12

, , Depth3

     Col1 Col2 Col3
Row1   13   15   17
Row2   14   16   18

, , Depth4

     Col1 Col2 Col3
Row1   19   21   23
Row2   20   22   24
    

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
Post a Comment (0)