Artificial Intelligence Lab: Bahria University, Islamabad
Artificial Intelligence Lab: Bahria University, Islamabad
Task # 1:
Make an R script for your first R program. Make a simple hello world program. Your program will
take name and age of user as input and store them in variable userName and userAge. Then it will
display the following line on screen (incremented user age)
Hello (userName)! You will be (userAge+1) years old next year.
Run your script through sourcing, as taught in tutorial given to you. Do not run line by line. (See the
hello world tutorial provided to you for this task)
Task # 2:
Open R Studio and run the following R programs. Try different values for separate runs of all
programs. Play around with the and run it again. See what happens. Make a note of what changes
you made and how it made the program behave. Also, if there are any errors, correct them and
write changes you made to remove the errors with output.
xor(x, y)
Output:
Output:
Output:
# Here are some built-in constants in R which you can use if you want. Run the following
commands and see what their output is.
> LETTERS
> letters
> pi
> month.name
> month.abb
Output:
> sum(2,7,5)
> x=c(2,NA,3,1,4)
> sum(x)
> sum(x, na.rm=TRUE) # this way we can ignore NA and NaN values
Output:
Create scripts for all the following tasks and source them for running. Paste code below the task
as well as snapshot of output.
Task # 3:
Create a vector of 15 elements. It must have two NA values. (see last part of task 2 for help) Do the
following with that vector.
a) Find out its sum, mean and prod using the following functions. sum() mean() prod(). Make
sure the result is not NA.
b) Find out the maximum and minimum value of the vector and the indexes of each. Also find
the range of the vector. For all operations use the following functions. min(), max(), range(),
which.min(), which.max().
c) Sorting of vectors can be done using the sort() function. By default, it sorts in ascending
order. To sort in descending order, we can pass decreasing=TRUE. Sort the vector in
ascending as well as descending order. Display the vector before sorting and display result
after sorting on screen. Was the original vector changed when your sorted?
vec=c(4,2,5,3,5,3,NA,43,6,3,44,NA,3,5,3)
print(paste("Sum: ",sum(vec,na.rm = TRUE)))
print(paste("Product: ",prod(vec,vec,na.rm = TRUE)))
print(paste("Mean: ",mean(vec,na.rm = TRUE)))
print(paste("Max: ",max(vec,na.rm = TRUE)))
print(paste("Min: ",min(vec,na.rm = TRUE)))
print(paste("Max Index: ",which.max(vec)))
print(paste("Min Index: ",which.min(vec)))
print(range(vec,na.rm = TRUE))
print(vec)
print(sort(vec,decreasing = FALSE))
print(sort(vec,decreasing = TRUE))
a=5
b=3
print(a*b)
print(a>b)
a1=c(3,2,4)
b1=c(4,7,8)
print(a1+b1)
print(a1<b1)