開始使用免費開始

R you functional?(2)

我們已為你提供一個可行的 interpret() 函式實作。在這個練習中,你將撰寫另一個函式,使用 interpret() 來解讀向量中你每日個人檔案瀏覽數的「所有」資料。此外,若有需要,你的函式還會回傳熱門日的總瀏覽次數。如果要遍歷整個向量,for 迴圈非常合適。是否回傳熱門日總瀏覽次數,可以透過帶有預設值的函式引數來實作。

本練習屬於課程

R 中級

檢視課程

練習說明

完成 interpret_all() 函式的樣板:

  • return_sum 設為可選引數,且預設為 TRUE
  • for 迴圈內遍歷所有 views:每次迭代都把 interpret(v) 的結果加到 count。記得 interpret(v) 會在熱門日回傳 v,否則回傳 0。同時,interpret(v) 也會印出一些訊息。
  • 完成 if 結構:
  • return_sumTRUE,回傳 count
  • 否則回傳 NULL

用這個新定義的函式分別對 linkedinfacebook 呼叫一次。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# The linkedin and facebook vectors have already been created for you
linkedin <- c(16, 9, 13, 5, 2, 17, 14)
facebook <- c(17, 7, 5, 16, 8, 13, 14)

# The interpret() can be used inside interpret_all()
interpret <- function(num_views) {
  if (num_views > 15) {
    print("You're popular!")
    return(num_views)
  } else {
    print("Try to be more visible!")
    return(0)
  }
}

# Define the interpret_all() function
# views: vector with data to interpret
# return_sum: return total number of views on popular days?
interpret_all <- function(views, return_sum) {
  count <- 0

  for (v in views) {

  }

  if (return_sum) {

  } else {

  }
}

# Call the interpret_all() function on both linkedin and facebook
編輯並執行程式碼