Run on web

https://www.jetbrains.com/datalore/buy/

https://posit.cloud/

Homework Code

## Rock Paper Scissor
## created by Apirak.A

#define a function to show final results
show_final_result <- function(user_score, bot_score) {
  print(paste("Your final score:", user_score)) #show current user result
  print(paste("Bot final score:", bot_score)) #show current bot result
  if (user_score > bot_score) {
    print("You win! 🎉")
    
  } else if (user_score < bot_score) {
    print("You Lose! ☠️")
  } else {
    print("It's a Tie! 😑")
  }
}

#define a function 'play' for run game
play <- function(){
  print("Welcome to Squid Game! 😈")
  print("You need to play 'Pao Ying Chub' Game! 😈")
  print("If you Lose, YOU DIE!!! 55555")
  print("=============================================")
  hands <- c("Scissor", "Paper", "Hammer") #define option to select
  r <- 1 #define round
  user_score <- 0 #define user score
  bot_score <- 0 #define bot score
  
  # Loop State
  repeat {
    print("Select Option below")
    print("[1]✌️ [2]🖐️ [3]✊ [4]🚪 (Exit)")
    user_input <- suppressWarnings(as.numeric(readline(prompt = "Enter a number (1-3) Enter 4 to exit: ")))
    
    #for other input that not matched 1-4
    if (is.na(user_input) || !(user_input %in% 1:4)) {
      print("Invalid input. Please enter a number between 1 and 4.") 
      next
    }
    
    #End Loop and show result
    if (user_input == 4) {
      show_final_result(user_score, bot_score)  # Call the function here
      break  # Exit the loop
    }
    
    #Play Loop 
    print("=============================================")
    print(paste("Round", r)) #Show round every time we play
    user_select <- hands[user_input] #get input from user
    print(paste("👨 You selected", user_select)) 
    bot_select <- sample(hands[1:3],1) #get random result from bot
    print(paste("🤖 Bot Selected", bot_select))
    
    #Calculate Result
    ## if result are same
    if (user_select == bot_select){ 
      print("TIE! 😑")
    } 
    ## if result are lose
    else if (user_select == "Scissor" & bot_select == "Hammer" | user_select == "Hammer" & bot_select == "Paper" | user_select == "Paper" & bot_select == "Scissor"){
      print("LOSE 😱")
      bot_score <- bot_score + 1 #Add score to bot
    } 
    ## if result are win
    else {
      print("WIN 😁")
      user_score <- user_score + 1 #Add score to user
    }
    print("=============================================")
    r <- r +1 #Add round number 
  }
}

play()

Result

[1] "Welcome to Squid Game! 😈"
[1] "You need to play 'Pao Ying Chub' Game! 😈"
[1] "If you Lose, YOU DIE!!! 55555"
[1] "============================================="
[1] "Select Option below"
[1] "[1]✌️ [2]🖐️ [3]✊ [4]🚪 (Exit)"
Enter a number (1-3) Enter 4 to exit: 1
[1] "============================================="
[1] "Round 1"
[1] "👨 You selected Scissor"
[1] "🤖 Bot Selected Hammer"
[1] "LOSE 😱"
[1] "============================================="
[1] "Select Option below"
[1] "[1]✌️ [2]🖐️ [3]✊ [4]🚪 (Exit)"
Enter a number (1-3) Enter 4 to exit: 2
[1] "============================================="
[1] "Round 2"
[1] "👨 You selected Paper"
[1] "🤖 Bot Selected Paper"
[1] "TIE! 😑"
[1] "============================================="
[1] "Select Option below"
[1] "[1]✌️ [2]🖐️ [3]✊ [4]🚪 (Exit)"
Enter a number (1-3) Enter 4 to exit: 1
[1] "============================================="
[1] "Round 3"
[1] "👨 You selected Scissor"
[1] "🤖 Bot Selected Scissor"
[1] "TIE! 😑"
[1] "============================================="
[1] "Select Option below"
[1] "[1]✌️ [2]🖐️ [3]✊ [4]🚪 (Exit)"
Enter a number (1-3) Enter 4 to exit: 1
[1] "============================================="
[1] "Round 4"
[1] "👨 You selected Scissor"
[1] "🤖 Bot Selected Scissor"
[1] "TIE! 😑"
[1] "============================================="
[1] "Select Option below"
[1] "[1]✌️ [2]🖐️ [3]✊ [4]🚪 (Exit)"
Enter a number (1-3) Enter 4 to exit: 3
[1] "============================================="
[1] "Round 5"
[1] "👨 You selected Hammer"
[1] "🤖 Bot Selected Paper"
[1] "LOSE 😱"
[1] "============================================="
[1] "Select Option below"
[1] "[1]✌️ [2]🖐️ [3]✊ [4]🚪 (Exit)"
Enter a number (1-3) Enter 4 to exit: 1
[1] "============================================="
[1] "Round 6"
[1] "👨 You selected Scissor"
[1] "🤖 Bot Selected Scissor"
[1] "TIE! 😑"
[1] "============================================="
[1] "Select Option below"
[1] "[1]✌️ [2]🖐️ [3]✊ [4]🚪 (Exit)"
Enter a number (1-3) Enter 4 to exit: 2
[1] "============================================="
[1] "Round 7"
[1] "👨 You selected Paper"
[1] "🤖 Bot Selected Paper"
[1] "TIE! 😑"
[1] "============================================="
[1] "Select Option below"
[1] "[1]✌️ [2]🖐️ [3]✊ [4]🚪 (Exit)"
Enter a number (1-3) Enter 4 to exit: 3
[1] "============================================="
[1] "Round 8"
[1] "👨 You selected Hammer"
[1] "🤖 Bot Selected Paper"
[1] "LOSE 😱"
[1] "============================================="
[1] "Select Option below"
[1] "[1]✌️ [2]🖐️ [3]✊ [4]🚪 (Exit)"
Enter a number (1-3) Enter 4 to exit: 1
[1] "============================================="
[1] "Round 9"
[1] "👨 You selected Scissor"
[1] "🤖 Bot Selected Hammer"
[1] "LOSE 😱"
[1] "============================================="
[1] "Select Option below"
[1] "[1]✌️ [2]🖐️ [3]✊ [4]🚪 (Exit)"
Enter a number (1-3) Enter 4 to exit: 2
[1] "============================================="
[1] "Round 10"
[1] "👨 You selected Paper"
[1] "🤖 Bot Selected Scissor"
[1] "LOSE 😱"
[1] "============================================="
[1] "Select Option below"
[1] "[1]✌️ [2]🖐️ [3]✊ [4]🚪 (Exit)"
Enter a number (1-3) Enter 4 to exit: 4
[1] "Your final score: 0"
[1] "Bot final score: 5"
[1] "You Lose! ☠️"
# Intro to R - DSB11
# Use Ctrl+Shift+C to change code > comment

##########################################
# 1 Variable
## variable cannot start with number
x <- 100
y <- 200
result <- x + y
result

## Snake Case Name
sales_2025 <- 50000 #recommend
sales.2026 <- 60000

## remove variable
rm(sales.2026)

## simple usecase
income <- 50000
expense <- 35000
saving <- income - expense
annual_saving <- saving * 12
print(saving)
print(annual_saving)

##########################################
# 2 Data Type
## Numeric (Number)
x <- 100; y <- 200; print(x+y)
## Character (text)
paste0("Banana","Orange","Grape") # Not add space
paste("Banana","Orange","Grape") # add space
## logical (Boolean)
TRUE
FALSE
T
F
10 > 2 #check true or false
(3+3) > 5 #check true or false
5 == 2+3 #check true or false
"hi" == "HI" #check 'is' >> true or false
"hi" != "Hi" #check 'is_not' >> true or false
!TRUE #reverse to FALSE
!FALSE #reverse to TRUE
## r is case_sensitive

## Date (YYYY-MM-DD)
## date ISO8601 >> "YYYY-MM-DD"
date_today <- "2025-02-08"
date_today <- as.Date(date_today) ##Important Command to replace data
class(date_today)

## Convert Data Type
as.character(100)
as.logical("FALSE")
as.numeric("5555") *2
as.Date("2025-02-08")

## Factor -> categorical data
gender <- c("m", "f","f","f","m")
gender <- as.factor(gender)
table(gender)

country <- c("th", "th", "uk", "us", "us", "kr", "jp", "jp", "th")
country <- as.factor(country)
table(country)

##########################################
# 3 Data Structures
## Vector*
1:10
seq(1,100,5) #sequence same like Excel
seq(from=1, to=100, by=5)
gpa <- c(a = 3.00, b = 4.00, c = 3.50, d = 2.45) # assign name to value

gpa[1:3] # subset by position
gpa[ c(1,3) ] # subset by position using concat
gpa["d"] # subset by name
gpa[ c("a","c","d") ] #subset by name using concat
gpa[gpa > 3] #subset by condiition
gpa[gpa <= 3] #subset by condition using concat

#vectorization
gpa + 0.01 # add 0.01 to all vector
gpa["a"] <- 3.45 #assign new data

gpa2 <- c(x = 3.78, y = 3.09)
final_grade <- c(gpa, gpa2)

## Matric = 2d vector
m <- matrix(1:10, ncol=5, byrow=T)
m * 2

m1 <- matrix(1:100, ncol=5, byrow=T)
m2 <- matrix(100:1, ncol=5, byrow=T)
m1 + m2

m3 <- matrix(c(2,5,4,10), ncol=2)
m3
m3[1,2] # get exactly subset data
m3[ ,2] # get all column
m3[1, ] # get all row

## List = playlist multiple data type
my_list <- list(
  name = "Bank",
  age = 34, 
  fav_movie = c("Star Wars",
                "LOTR",
                "Harry Potter"),
  netflix_sub = T,
  hbogo_sub = F
)

my_list[["fav_movie"]][1]
my_list[["fav_movie"]][2:3]
my_list[["fav_movie"]][c(1,3)]

my_list$name
my_list$fav_movie[3]

# Dataframe
id <- 1:5
name <- c("Bank", "Jam", "Pangping", "PangYen","Junepang")
netflix_sub <- c(T, T, F, F, T)
spending <- c(200,250,300,230,200)

df <- data.frame(id, name, netflix_sub, spending)
length(name) #check length
dim(df) # check dimension

df[c(1,3,4), c("name", "spending")] #subset by position
df[df$spending >= 250, ] #subset by condition

df$total_stream <- df$spending + 300 # add new column
df$total_stream <- NULL # remove column

df[df$netflix_sub, ]
netflix_fan <- df[df$netflix_sub, ]

write.csv(netflix_fan, "netflix_fan.csv", row.names=F) # create csv file without row number

## NA is NULL in SQL

##########################################
# 4 Function

add_two_nums <- function(num1, num2) {
  return(num1 + num2)
}

add_two_nums <- function(num1, num2) {
  num1 + num2
}

add_two_nums2 <- function(x,y) x+y
showresult <- add_two_nums(5,20)

greeting <- function(name){
  result <- paste("Hi!", name)
  return(result)
}

cube <- function(base, power){
  base ** power
}

##########################################
# 5 Control Flow

#if else

grading <- function(score){
  if (score >=80) {
    return("A")
  } else if (score >= 70) {
    return("B")
  } else if (score >= 60) {
    return("C")
  } else if (score >= 50) {
    return("D")
  } else {
    return("F")
  }
}

name <- readline("What is your name: ")
hands <- c("hammer", "scissor", "paper")
sample()

#Homework -> Pao Ying Chub