### Welcome to the Simplilearn Community

Want to join the rest of our members? Sign up right away!

# DS with R | Nimisha | Jan 4th

#### Raju Pratap

##### Member
Happy Learning !!
Hello

#### Ahmed Rashed

##### Member
Hi Nimisha, I am marked absent of today's session (Jan 7th) on the live class of R but I was there all the class. Could you please fix this. Ahmed Rashed

#### Bhanu Pratap Singh_13

##### Member
find factorial of a number

############################################ why line above need to be excuted sapratly##############
factorial = 1
if(num < 0) {
} else if(num == 0) {
print("The factorial of 0 is 1")
} else {
for(i in 1:num) {
factorial = factorial * i
}
print(paste("The factorial of", num ,"is",factorial))
}

• Judith reya

#### Shreeharsha Bhat

##### Member
find factorial of a number

############################################ why line above need to be excuted sapratly##############
factorial = 1
if(num < 0) {
} else if(num == 0) {
print("The factorial of 0 is 1")
} else {
for(i in 1:num) {
factorial = factorial * i
}
print(paste("The factorial of", num ,"is",factorial))
}

Try this code. I too don't understand why your codes need the execute part alone first # factorial of a number
######### Execute this First and only once ######################
fact <- function(num1){
if(num1 == 0){
print("There cant be any factorial for 0")
}else {
factorial = 1
for (num in num1:1){
factorial = factorial * num
}
cat ("the factorial is : " ,factorial)
}
}
####### execute only this statement every time you want to calculate factorial ###########

#### Shikha Khare

##### Member
# take input from the user
num = as.integer(readline(prompt="Enter a number: "))
factorial = 1
# check is the number is negative, positive or zero
if(num < 0) {
print("Sorry, factorial does not exist for negative numbers")
} else if(num == 0) {
print("The factorial of 0 is 1")
} else {
for(i in 1:num) {
factorial = factorial * i
}
print(paste("The factorial of", num ,"is",factorial))
}

Error : Error in if (num < 0) { : missing value where TRUE/FALSE needed

#### Sachida Nand Tripathi

##### Customer
Customer
info <- function(name,age,qual,hobb, org='CGI')
{
cat('Name = ', name, '\nAge = ', age, '\nQualification=',
qual, '\nHobbie=', hobb, '\nOrgainisation',org)
}

factorial <- function(num=0){
fact=1
l_num = num
while (l_num>0) {
fact = fact*l_num
l_num <- l_num - 1

}
cat(' Factorial of ',num, ' is ', fact)
}

factorial(5)

check_prime <- function(num=0){
divisor_limit = num%/%2
divisor = 2
is_prime = TRUE
if(num==0 || num==1) {
cat(num ,' is not a prime number!!!')
}
else{
while (divisor<= divisor_limit){
if (num%%divisor == 0){
cat(num ,' is not a prime number!!!')
is_prime = FALSE
break
}
divisor <- divisor + 1
}
if (is_prime){
cat(num ,' is a prime number!!!')
}

}
}

check_prime(100000)

rock_paper_scissor <- function(){
chances <- 3
round <- 1
Player1.win <- 0
Player2.win <- 0
while (chances>0){
cat('Round ->>',round)
choice1 <- readline('Enter your choice (Rock or Paper or Scissor) Player 1:')
cat('\014')
choice2 <- readline('Enter your choice (Rock or Paper or Scissor) Player 2:')
cat('\014')

if (choice1 == 'Rock' && choice2=='Scissor'){
Player1.win <- Player1.win + 1

}
else if(choice1 == 'Scissor' && choice2=='Rock'){
Player2.win <- Player2.win + 1
}
else if (choice1 == 'Scissor' && choice2=='Paper'){
Player1.win <- Player1.win + 1
}
else if (choice1 == 'Paper' && choice2=='Scissor'){
Player2.win <- Player2.win + 1
}
else if (choice1 == 'Paper' && choice2=='Rock'){
Player1.win <- Player1.win + 1
}
else if (choice1 == 'Rock' && choice2=='Paper'){
Player2.win <- Player2.win + 1
}
chances <- chances - 1
round <- round + 1
}
choice = readline('Do you want to see result (Yes/No)')
if (choice== 'Yes'){
if (Player1.win > Player2.win){
print('Player 1 is the winner')
}
else{
print('Player 2 is the winner')
}
}
else{
print('You choose to not see result!!! Good bye!!!')
}
}

rock_paper_scissor()

#### Bhanu Pratap Singh_13

##### Member
# Rock Paper Scissor
Game<- c("Rock1", "Paper" ,"Scissor" )
Game
Rock_wins<-0
Scissor_wins<-0
Paper_wins<-0

if(Player_1==Player_2)
{
print("Try Again")
}else

if(Player_1=="Rock1" && Player_2=="Scissor")
{
print("Rock crushes Scissor,--> Rock wins")
Rock_wins<-Rock_wins+1
}else
if(Player_1=="Scissor"&& Player_2=="Paper")
{
print("Scissor cuts Paper -> Scissor wins")
Scissor_wins=Scissor_wins+1

}else
if(Player_1=="Paper"&& Player_2=="Rock1")
{
print("# Paper covers Rock ----> Paper wins")
Paper_wins=Paper_wins+1
}else
if(Player_1=="Rock1" && Player_2=="Paper")
{
print("Rock crushes Scissor,--> Rock wins")
Rock_wins<-Rock_wins+1
}else
if(Player_1=="Scissor"&& Player_2=="Rock1")
{
print("Scissor cuts Paper -> Scissor wins")
Scissor_wins=Scissor_wins+1
}else
if(Player_1=="Paper"&& Player_2=="Scissor")
{
print("# Paper covers Rock ----> Paper wins")
Paper_wins=Paper_wins+1
}else{print("invalid option")}

#### Vivian Koneri

##### Member
################################# Find factorial of a number ###############

factorial(num){ # defining a function for finding the factorial of a number
fact <- 1
while (num > 0){

fact = num * fact
num = num - 1
}
print(fact)
}

factorial(5)

############### GAME OF ROCK, SCISSORS and PAPER ###############

Score_P1 <- 0 # Initialize the score of Player-1 to 0 at the start
Score_P2 <- 0 # Initialize the score of Player-2 to 0 at the start

while ( (Score_P1 + Score_P2) < 5 ){ # Executing the LOOP for best of FIVE scores before declaring the winner

choice <- c('Rock', 'Paper', 'Scissors')
p1 <- sample(choice, size=1, replace = TRUE)
p2 <- sample(choice, size=1, replace = TRUE)

if (p1 == 'Rock' && p2 == 'Paper'){
Score_P2 = Score_P2 +1
}else if (p1 == 'Rock' && p2 == 'Scissors'){
Score_P1 = Score_P1 + 1
}else if (p1 == 'Paper' && p1 == 'Rock'){
Score_P1 = Score_P1 +1
}else if (p1 == 'Scissors' && p2 == 'Rock'){
Score_P2 = Score_P2 + 1
}else if (p1 == 'Paper' && p2 == 'Scissors'){
Score_P2 = Score_P2 + 1
}else if (p1 == 'Scissors' && p2 == 'Paper'){
Score_P1 = Score_P1 + 1
}else {
}
}
print(paste("Score of Player 1: ", Score_P1))
print(paste("Score of Player 2: ", Score_P2))
if (Score_P1 > Score_P2){
print('Congratulations Player 1 you are the Winner!')
}else{
print('Congratulations Player 2 you are the Winner!')
}

############################ Prime Numbers ###########################

#Solution for part a:-

# Program to check if the input number is prime or not
# taking a number input from the user

num = as.integer(readline(prompt="Enter a number: "))
flag = 0
# prime numbers are greater than 1
if(num > 1) {
# check for factors
flag = 1
for(i in 2:num-1)) {
if ((num %% i) == 0) {
flag = 0
break
}
}
}
if(num == 2) flag = 1
if(flag == 1) {
print(paste(num,"is a prime number"))
} else {
print(paste(num,"is not a prime number"))
}

#Solution for part b:-
######### Identify Prime numbers from a vector of numbers ##############################

vec_num1 <- c(sample(seq(1:1000), size = 100))
vec_num1

prime_nums1 = c()
for ( j in 1:length(vec_num1)){
flag = 0
# prime numbers are greater than 1
if(vec_num1[j] > 1) {
# check for factors
flag = 1
for(i in 2:vec_num1[j]-1)) {
if ((vec_num1[j] %% i) == 0) {
flag = 0
break
}
}
}
if(num == 2) flag = 1
if(flag == 1) {
prime_nums1 = c(prime_nums1, vec_num1[j])
} else {
}
}

prime_nums1

#Solution for part c:-
######### Identify Prime numbers from 2000 to 3000 ###############################

vec_num <- 2000:3000
vec_num
prime_nums = c()
for ( j in 1:length(vec_num)){
flag = 0
# prime numbers are greater than 1
if(vec_num[j] > 1) {
# check for factors
flag = 1
for(i in 2:vec_num[j]-1)) {
if ((vec_num[j] %% i) == 0) {
flag = 0
break
}
}
}
if(num == 2) flag = 1
if(flag == 1) {
prime_nums = c(prime_nums, vec_num[j])
} else {
}
}

prime_nums

#Solution for part d:-
############## Identify Prime numbers from a vector of numbers n numbers ###################

prime_numbers <- function(n) {
if (n >= 2) {
x = seq(2, n)
prime_nums = c()
for (i in seq(2, n)) {
if (any(x == i)) {
prime_nums = c(prime_nums, i)
x = c(x[(x %% i) != 0], i)
}
}
return(prime_nums)
}
else
{
stop("Input number should be at least 2.")
}
}

prime_numbers(50)

###################################### END of ASSIGNMENT - 1 #################################

Last edited:

#### Sravan Kumar Eligati

##### Member
# Question 1: Find factorial of a number
factorial(6)
# OR
f <- 10
for (i in f){
j <- 1
for (i in 1:f){
j <- j * i
}
print(j)
}
# OR
f <- 10
while (TRUE){
if (f == 0){
print(0)
break
} else if (f > 0){
j <- 1
while (TRUE){
j <- j * f
f <- f - 1
if (f == 0)
break
}
print(j)
break
}
}
# Question 2:
# Rock Paper Scissor
while (TRUE){
ans <- readline("Would you like to play the Rock Paper Scissor game (Y/N) ? ")
if(ans == 'N'){
print ('Exiting from the game')
ans <- c()
break
} else if(ans != 'Y'){
print ('You have entered invalid input and you are exiting from the game')
ans <- c()
break
} else {
print('You are about to play Rock Paper Scissor')
print('----------------------------------------------------------------------------------------------')
print('Note: Only 2 players are required to play the game')
print('Note: Players has to play 5 games and winner is declared based on output from the 5 games')
print('Note: Players has to choose the valid choices as: ')
print('1. Rock')
print('2. Paper')
print('3. Scissor')
print('----------------------------------------------------------------------------------------------')
player1 <- readline('Enter Player1 Name: ')
player2 <- readline('Enter Player2 Name: ')
cat(player1, ' & ', player2, ', the game is ON', '\n')
p1 <- 0
p2 <- 0
for (i in 1:5){
cat('Game :', i, '\n')
print(player1)
print(player2)
if((ip1 == 1 && ip2 == 1) || (ip1 == 2 && ip2 == 2) || (ip1 == 3 && ip2 == 3)){
p1 <- p1 + 1
p2 <- p2 + 1
} else if ((ip1 == 2 && ip2 == 1) || (ip1 == 1 && ip2 == 3) || (ip1 == 3 && ip2 == 2)){
p1 <- p1 + 1
} else if ((ip1 == 1 && ip2 == 2) || (ip1 == 3 && ip2 == 1) || (ip1 == 2 && ip2 == 3)){
p2 <- p2 + 1
}
ip1 <- c()
ip2 <- c()
}
cat(ip1, ip2, '\n')
if(p1 > p2){
cat ('Congratulations ', player1, ', you have won the game', sep = '', '\n')
} else if (p2 > p1){
cat ('Congratulations ', player2, ', you have won the game', sep = '', '\n')
} else {
cat (player1, ' & ', player2, ', the game is draw', sep = '', '\n')
}

player1 <- c()
player2 <- c()
ans <- c()
break
}
}
# Question 3:
# prime numbers :
# a. check whether a number is prime or not
# b. from a vector of numbers identify all the prime numbers
prime <- c(1, 2, 3, 4, 5, 6)
prime <- sample(20)
for (i in prime){
flag <- 0
if (i == 1){
cat(i, ' is a NOT Prime Number', sep ='', '\n')
} else if (i == 2) {
cat(i, ' is a Prime Number', sep ='', '\n')
} else {
for (j in 3:i-1) {
if(i %% j == 0){
flag <- 1
}
}
if(flag == 1){
cat(i, ' is a NOT Prime Number', sep ='', '\n')
} else {
cat(i, ' is a Prime Number', sep ='', '\n')
}
}
}
# c. create a vector of all the prime numbers in between 2000 and 3000
prime <- 2000:3000
flag <- 0
cnt <- 0
for (i in prime){
if (i == 1){
next
} else if (i == 2) {
cnt <- 1
cat(i, ' is a Prime Number', sep ='', '\n')
} else {
for (j in 3:i-1) {
if(i %% j == 0){
flag <- 1
}
}
if(flag != 1){
cnt <- cnt + 1
cat(i, ' is a Prime Number', sep ='', '\n')
}
}
flag <- 0
}
# d. create a vector of first 50 prime numbers
prime <- sample(1000, 500)
prime
flag <- 0
cnt <- 0
for (i in prime){
if (i == 1){
next
} else if (i == 2) {
cnt <- 1
cat(i, ' is a Prime Number', sep ='', '\n')
} else {
for (j in 3:i-1) {
if(i %% j == 0){
flag <- 1
}
}
if(flag != 1){
cnt <- cnt + 1
cat(i, ' is a Prime Number', sep ='', '\n')
if (cnt == 50){
break
}
}
}
flag <- 0
}

#### Bhanu Pratap Singh_13

##### Member
############Prinme Number################

targate = 1:1000
r<-c()
for(l in targate){
if (l == 0){
next
} else if (l == 1){
next
} else if(l == 2){
l = 2
} else if (l %% 2 == 0){
next
} else if (l == 3){
l = 3
} else if (l %% 3 == 0){
next
} else if (l == 5){
l = 5
} else if (l %% 5 == 0){
next
}
r<-c(r,l)
}
##First 50

r[1:50]

Hello

#### SWATI SHAYNA

##### Active Member
Alumni
###################How to find factorial of a number using function and for loop in R###########################

find_factorial = function(n){
factorials = 1
if (n < 0){
print("factorial of a negative number is not possibbe")
}else if(n ==0) {
print("Factorial of 0 is 1")
cat( factorials)
}else{
for(i in 1: n){
factorials = factorials * i
}
return(factorials)
}}

#### SWATI SHAYNA

##### Active Member
Alumni
# take input from the user
num = as.integer(readline(prompt="Enter a number: "))
factorial = 1
# check is the number is negative, positive or zero
if(num < 0) {
print("Sorry, factorial does not exist for negative numbers")
} else if(num == 0) {
print("The factorial of 0 is 1")
} else {
for(i in 1:num) {
factorial = factorial * i
}
print(paste("The factorial of", num ,"is",factorial))
}

Error : Error in if (num < 0) { : missing value where TRUE/FALSE needed

#############################################################################################################
###########################################################################################################
num = as.integer(readline("Enter a number: "))
factorial = 1
# check is the number is negative, positive or zero
if(num < 0){
print("Sorry, factorial does not exist for negative numbers")
}else if(num == 0) {
print("The factorial of 0 is 1")
} else {
for(i in 1:num) {
factorial = factorial * i
}
print(paste("The factorial of", num ,"is",factorial))
}

try this code!

you are getting the error because your num is not assigned with any value(because you are executing all your code at once) and if statement needs some value for num to compare(num>0--- here num is NA)

and execute in 3 steps !
step1: where you are taking input from user i.e. very first line
step 2: factorial = 1
step 3: your if block statement
(you can execute step 2 and step 3 together)

#### SWATI SHAYNA

##### Active Member
Alumni
#########################ROCK_PAPER_SCISSOR -- Using Function#################################################

rock_paper_scissor = function(n1 , n2 ){
if (n1==n2){
print("draw")
}else if(n1 == 'ROCK' & n2 == 'SCISSOR'){
print("n1 wins")
}else if(n1 == ' SCISSOR' & n2 == 'PAPER'){
print("n1 wins")
}else if(n1=='PAPER' & n2 == 'ROCK'){
print("n1 wins")
}else if(n2 == 'ROCK' & n1 == 'SCISSOR'){
print("n2 wins")
}else if(n2 == ' SCISSOR' & n1 == 'PAPER'){
print("n2 wins")
}else if(n2=='PAPER' & n1 == 'ROCK'){
print("n2 wins")
}else{
WARNING: choose upper case")
}
}

#### SWATI SHAYNA

##### Active Member
Alumni
rps <- function (move) {
opts <- c("rock", "paper", "scissors")
stopifnot(length(move) == 1L, move %in% opts)
cpu <- sample(opts, 1)
names(cpu) <- if (identical(move, cpu)) {
"tie"
}
else if (move == "rock" & cpu == "scissors" | move == "paper" &
cpu == "rock" | move == "scissors" & cpu == "paper") {
"win"
}
else {
"loss"
}
cpu
}

I copied this code from stackoverflow and I am not able to understand line number3 and line number 5: , infact the complete code is too difficult for me to understand. I posted this query in the morning also but somehow it was rejected

#### Rutuja Saste

##### Member
#find factorial
repeat{
ans<-1
no<-as.integer(readline(prompt = 'enter a no to find factorial '))
for(i in 1:no){
ans<-ans*i
}
cat('factorial of a no is ',ans)
qn<-readline('do u want to continue? ')
if(qn=='n')
break
}

#### Rutuja Saste

##### Member
#check whether no is prime or not

repeat{
no<-as.integer(readline(prompt = 'enter no to check whether it is prime or not '))
a=0
if(no>1){
a=1
for(i in 2 no-1)){
if(no%%i==0){
a=0
break
}
}
}
if(no==2) a=1
if(a==1){
print('no is prime ')
}else{
print('number is not prime ')
qn<-readline('do you want to continue? ')
if(qn=='n')
break
}
}

#---------------------------------------------------------------------------

#create vector of prime no from a given range

vec<-start:end
#vec
#length(vec)
prime<-c()
for(i in 1:length(vec)){
a=0
if(vec>1){
a=1
for(j in 2 vec-1)){
if(vec%%j==0){
a=0
break

}
}

}
if(a==1)
prime<-c(prime,vec)

}
cat("prime no from given range are : \n",prime)

#---------------------------------------------------------------------------
#from a given vector identify all prime no

number<-c(55,67,11,99,34,22,31,777,81,19,5,37,45)
number
vec<-c()
for(i in 1:length(number)){
a=0
if(number>1){
a=1
for(j in 2 number-1)){
if(number%%j==0){
a=0
break
}
}
}

if(a==1){
vec<-c(vec,number)
}

}
cat('prime no from given vector are \n ',vec)
#----------------------------------------------------------------------

#program for first n prime no

count<-as.integer(readline(prompt = 'how many prime no do you want? '))
a<-2
while(count!=0){
for (i in 2:a ) {
if(a%%i==0){
break
}
}
if(i==a){
cat(a,' ')
count=count-1
}

a<-a+1
}

#### Rutuja Saste

##### Member
# Q1--------rock paper scissor---------------------------------------------

while(TRUE){
ans<-readline('do you want to play? yes or no ')
if(ans=='no'){
break
}else{
print('To play game it require 2 players')
print('A.Rock,B. Scissor,C. Paper ')
print(player1)
print(player2)

if(opt1=='A' & opt2=='A'){
print('its tie')
}else
if(opt1=='A' & opt2=='B'){
cat('rock crushes scissor so winner is : ', player1)
}else
if(opt1=='A' & opt2=='C'){
cat('rock crushes scissor so winner is : ', player2)
}else
if(opt1=='B' & opt2=='C'){
cat('rock crushes scissor so winner is : ', player1)
}else
if(opt1=='B' & opt2=='A'){
cat('rock crushes scissor so winner is : ', player2)
}else
if(opt1=='B' & opt2=='B'){
print('its tie')
}else
if(opt1=='C' & opt2=='C'){
print('its tie')
}else
if(opt1=='C' & opt2=='A'){
cat('rock crushes scissor so winner is : ', player1)
}else
if(opt1=='C' & opt2=='B'){
cat('rock crushes scissor so winner is : ', player2)
}

}

}

# Q2-----------------rock paper scissor------user playing 5 times------------

while(TRUE){
ans<-readline('do you want to play? yes or no ')
if(ans=='no'){
break
}else{
print('To play game it require 2 players')
print('A.Rock,B. Scissor,C. Paper ')
p1<-0
p2<-0
for(i in 1:5){
print(player1)
print(player2)

if(opt1=='A' & opt2=='A'){
p1<-p1+1
p2<-p2+1

}else
if(opt1=='A' & opt2=='B'){
p1<-p1+1

}else
if(opt1=='A' & opt2=='C'){
p2<-p2+1

}else
if(opt1=='B' & opt2=='C'){
p1<-p1+1

}else
if(opt1=='B' & opt2=='A'){
p2<-p2+1

}else
if(opt1=='B' & opt2=='B'){
p1<-p1+1
p2<-p2+1

}else
if(opt1=='C' & opt2=='C'){
p1<-p1+1
p2<-p2+1

}else
if(opt1=='C' & opt2=='A'){
p1<-p1+1

}else
if(opt1=='C' & opt2=='B'){
p2<-p2+1

}
opt1<-c()
opt2<-c()

}
if(p1>p2){
cat('winner is : ',player1)
}else if(p2>p1){
cat('winner is : ',player2)
}else
{
print('its tie')
}
}
}

#### Sohrab Khalili

##### Member
Happy Learning !!

# prepare a rock-paper-scissor game and decide using best out of 5

rs <- function(){
#Rock scissors

# r p s
# r 3 0 1
# p 1 3 0
# s 0 1 3
rule <- matrix(c(3,1,0,0,3,1,1,0,3), nrow = 3, ncol = 3, byrow = FALSE,
dimnames = (list(c('r','p','s'),c('r','p','s'))))
player1<-list(name='',score=0,action=c())
player2<-list(name='',score=0,action=c())
for (i in 1:5){
}
for (i in 1:5){
}
for (i in 1:5){
print(i)
if (rule[player1\$action,player2\$action] == 0) {
player2\$score = player2\$score + 1
} else if (rule[player2\$action,player1\$action] == 0) {
player1\$score = player1\$score + 1
}
}
if (player1\$score > player2\$score) {
print (paste('congratulations',player1\$name,'you won',player1\$score,'to',player2\$score))
}
else if (player2\$score > player1\$score) {
print (paste('congratulations',player2\$name,'you won',player2\$score,'to',player1\$score))
}
else {
print ('it\'s a draw')
}
}
rs()

# a. check whether a number is prime or not

isPrime <- function (n){
prime<-T
for (i in 2:n-1) {
if (n %% i == 0) {
prime<-F
break
}
}
if (n == 2 || n == 1) {prime = T}

return (prime)
}
isPrime(3)

#### Chirag Dhaifule

##### Member
Happy Learning !!

a <- 1
while (n >=1){
a <- a*n
n <- n-1
}
a

#### Vivian Koneri

##### Member
########## Date : Jan 12 2021 - Example for using cbind, created a column MPG_avg and insert it ahead of MPG_City###########

cars <- read.csv(file.choose(), stringsAsFactors = TRUE)

m <- cars

m\$MPG_avg <- (m\$MPG_City + m\$MPG_Highway)/2

m <- cbind(m)[, c(1,2,3,4,5,6,7,8,9,10,16,11,12,13,14,15)]

#### Ashwin V Nair

##### Member
Date: Jan 12 2021 - Task - Create a column MPG and insert average of MPG_City and MPG_Highway before MPG_City

MPG <- rowMeans(cars[,c('MPG_City', 'MPG_Highway')], na.rm=TRUE)

cars <- cbind(cars[,1 : (which(colnames(cars) == 'Horsepower'))],
MPG , cars[, (which(colnames(cars) == 'Horsepower')+1): ncol(cars)])

Last edited:

#### Vijaya Kumar Avvaru

##### New Member
# add a new column as MPG which avg of MPG_City & MPG_Highway immediately before MPG_City

I am able to get the output with below code:

MPG = c()

for(i in 1: ncol(cars) ){
MPG = (cars\$MPG_City + cars\$MPG_Highway) %/% 2
}

New_cars = cbind(cars[,1 which(colnames(cars) == 'MPG_City')-1)], MPG,cars[,(which(colnames(cars) == 'MPG_City'):ncol(cars))] )

But, I tried using sapply, which is not working. I am not getting the mean of the column MPG_City and Highway. only I am getting MPG_City value to MPG vector. Need to understand why

MPG = sapply(c(cars\$MPG_City, cars\$MPG_Highway), mean )

#### Shweta_116

##### New Member
Date : 12th Jan 2021
ROCK PAPER SCISSOR GAME CODE

################ ROCK PAPER SCISSOR GAME CODING ######################
chance <- 1
rounds <- 3
ctr1 <- 0
ctr2 <- 0
YN <- 'Y'
{
print('Game Starts! Player1 and Player2 at 0-0')
if(YN == 'Y')
{
chance <- 1
while (chance <= 3 && YN == 'Y')
{
print('Rock Paper Scissor')
print(choice1)
print(choice2)
if(choice1 == choice2)
print('Its a foul!')
if((choice1== 'Scissor') && (choice2 == 'Rock'))
{ print('Rock crushes Scissor')
print('Player2 wins this chance')
ctr2 <- ctr2 +1
}
else if((choice2 =='Scissor') && (choice1 == 'Rock'))
{print('Rock crushes Scissor')
print('Player1 wins this chance')
ctr1 <- ctr1 +1
}
else if((choice1== 'Scissor') && (choice2 == 'Paper'))
{print('Scissor cuts the Paper')
print('Player1 wins this chance')
ctr1 <- ctr1 +1
}
else if((choice2== 'Scissor') && (choice1 == 'Paper'))
{print('Scissor cuts the Paper')
print('Player2 wins this chance')
ctr2 <- ctr2 +1
}
else if ((choice1 == 'Paper') && (choice2 == 'Rock'))
{print('Paper covers the Rock')
print('Player1 wins this chance')
ctr1 <- ctr1 +1
}
else if ((choice2 == 'Paper') && (choice1 == 'Rock'))
{print('Paper covers the Rock')
print('Player2 wins this chance')
ctr2 <- ctr2 +1
}
chance <- chance + 1
YN <- readline('Do you wish to continue? : Y/N ')
}

}
if(ctr1 > ctr2)
print('Player1 wins the Game!')
else
print('Player2 wins The Game!')
}

===============================================================

Output :
 "Game Starts! Player1 and Player2 at 0-0"
 "Rock Paper Scissor"
Player1 plz enter your choice Paper
 "Paper"
Player2 plz enter your choice Scissor
 "Scissor"
 "Scissor cuts the Paper"
 "Player2 wins this chance"
Do you wish to continue? : Y/N Y
 "Rock Paper Scissor"
Player1 plz enter your choice Paper
 "Paper"
Player2 plz enter your choice Paper
 "Paper"
 "Its a foul!"
Do you wish to continue? : Y/N N
 "Player2 wins The Game!"

#### Sravan Kumar Eligati

##### Member
Date: 12 Jan 2021; Task - add a new column as MPG which is a average of MPG_City & MPG_Highway immediately before MPG_City

MPG <- (cars\$MPG_City+cars\$MPG_Highway)/2
# OR
MPG = rowMeans(cars[, c('MPG_City', 'MPG_Highway')], na.rm = TRUE)
cars1 <- cbind(cars[1 : (which(colnames(cars) == 'MPG_City')-1)], MPG, cars[(which(colnames(cars) == 'MPG_City'): ncol(cars))])

#### Vidya V_3

##### Member
12.01.21
Task : add a new column as MPG which avg of MPG_City & MPG_Highway immediately before MPG_City

MPG<-c()
MPG<-apply(cars[11:12],FUN= mean,MARGIN=1)
cars<-cbind(cars[1:10],MPG,cars[11:ncol(cars)])

#### Rutuja Saste

##### Member
# add a new column as MPG which avg of MPG_City & MPG_Highway immediately before MPG_City

colnames(cars)
cars[c('MPG_City','MPG_Highway')]
which(names(cars)=='MPG_City')
which(names(cars)=='MPG_Highway')
MPG<-rowSums(cars[c('MPG_City','MPG_Highway')])/2
MPG
ncol(cars)
cars_newcol<-cbind(cars[,1:10],MPG,cars[,11:15])
colnames(cars_newcol)
ncol(cars_newcol)
cars_newcol[c('MPG_City','MPG_Highway','MPG')]

#### Raju Pratap

##### Member
# add a new column as MPG which avg of MPG_City & MPG_Highway immediately before MPG_City

# 1. find position of MPG_City column
which(colnames(cars) == 'MPG_City')
#position for new column=(MPG_City)-1
cars['MPG'] <- (cars\$MPG_City+cars\$MPG_Highway)/2

colnames(cars)
cars2 <- cars[, c(1:10,17,11:16)]
cars <-cars2
View(cars)

#### Chirag Dhaifule

##### Member
Unable to login for today's class. Is there any problem with servers at Simplilean. Getting the following message - Dear learner, due to the high volume of learners, class attendance and recordings for your live class sessions might not be reflecting at this time. We are working on it and we should be able to resolve this issue shortly. Happy learning!

#### Hussain shaik_1

##### New Member
Hi Nimisha, I am marked absent of today's session (Jan 7th) on the live class of R but I was there all the class. Could you please fix this. Ahmed Rashed

may I know, where can I find attendance details? url plz.

#### Angalakuduru Harsha Vardhan

##### Active Member
Alumni
Should we complete all the topics covered in Elective course - Statistics with Data Science to get on for the upcoming live class !? @Nimisha mam

#### Sohrab Khalili

##### Member
Happy Learning !!

Hi Nimisha

In your last class you wrote:
View(cars[order(cars\$Make,cars\$MSRP,
decreasing = c(FALSE,TRUE)),])

It seems that you cannot order multicolumns with the c(FALSE,TRUE). It doesnt seem to work for the second column. You need to order them in two steps. Any other way to do this ?

#### Angalakuduru Harsha Vardhan

##### Active Member
Alumni
Is there any self learning video regarding the presentile and quantile concept @Nimisha mam

• SWATI SHAYNA

#### Rutuja Saste

##### Member
Is there any self learning video regarding the presentile and quantile concept @Nimisha mam
I think no self learning videos but you can refer youtube

#### Angalakuduru Harsha Vardhan

##### Active Member
Alumni
I think no self learning videos but you can refer youtube
It was getting deviated in google opening several tabs just like that listening to the unknown things, So I asked for that .Thanks

#### SWATI SHAYNA

##### Active Member
Alumni
How to plot a large number of data on x axis in stacked chart?
For example: 45 values need to be presented in a stacked chart

#### SWATI SHAYNA

##### Active Member
Alumni
How to plot a large number of data on x axis in stacked chart?
For example: 45 values need to be presented in a stacked chart

#### SWATI SHAYNA

##### Active Member
Alumni
# take input from the user
num = as.integer(readline(prompt="Enter a number: "))
factorial = 1
# check is the number is negative, positive or zero
if(num < 0) {
print("Sorry, factorial does not exist for negative numbers")
} else if(num == 0) {
print("The factorial of 0 is 1")
} else {
for(i in 1:num) {
factorial = factorial * i
}
print(paste("The factorial of", num ,"is",factorial))
}

Error : Error in if (num < 0) { : missing value where TRUE/FALSE needed
################################
num = as.integer(readline("Enter a number: "))
factorial = 1
# check is the number is negative, positive or zero
if(num < 0){
print("Sorry, factorial does not exist for negative numbers")
}else if(num == 0) {
print("The factorial of 0 is 1")
} else {
for(i in 1:num) {
factorial = factorial * i
}
print(paste("The factorial of", num ,"is",factorial))
}

try this code!

you are getting the error because your num is not assigned with any value(because you are executing all your code at once) and if statement needs some value for num to compare(num>0--- here num is NA)

and execute in 3 steps !
step1: where you are taking input from user i.e. very first line
step 2: factorial = 1
step 3: your if block statement
(you can execute step 2 and step 3 together)

#### SWATI SHAYNA

##### Active Member
Alumni

Question: Provide state wise status of complaints in a stacked bar chart.
here in this case there are total of 43 states , how this can be presented in a stacked chart

#### Vivian Koneri

##### Member
### Project - 6 DS with R ####
### E-commerce - To segment the customers with RFM calculations ###

### Ingesting Data ####
View(e_data)
data1 <- e_data
str(data1)

library(dplyr)
library(lubridate)

#### Data cleaning #####
#### All values less than 0 are converted to NA and then dropped ####
data1 <- data1 %>%
mutate(Quantity = replace(Quantity, Quantity<=0, NA),
UnitPrice = replace(UnitPrice, UnitPrice<=0, NA))

data1 <- data1 %>%
drop_na()

#### converting character variable to factor #####
#### converting Date from 'char' to 'Date' ####

data1 <- data1 %>%
mutate(InvoiceNo=as.factor(InvoiceNo), StockCode=as.factor(StockCode),
InvoiceDate=parse_date_time(InvoiceDate, "ymd"), CustomerID=as.factor(CustomerID),
Country=as.factor(Country))

data1 <- data1 %>%
mutate(total = Quantity*UnitPrice)

#### RFM calculations #########

df_RFM <- data1 %>%
group_by(CustomerID) %>%
summarise(recency=as.numeric(parse_date_time("2018-01-01")-max(InvoiceDate)),
frequency=n_distinct(InvoiceNo), monetary= sum(total)/n_distinct(InvoiceNo))

str(df_RFM)

#### ERROR - Recency is not getting calculated properly as number of days ###
#### Request your guidance to get a proper numeric value for recency ###

• Rutuja Saste

#### Sanjeev Kumar_65

##### Member
is there limitations of hours of using Simplilearn lab? How can we use lab further if already crossed limits???