開始使用免費開始

將資料框用 glue 串接

資料常以 data frame 儲存。我們常希望產出的分析也能讓人容易閱讀。舉例來說,列印一句描述資料框大小的句子就很有幫助。把 glue()nrow()ncol() 結合,你可以回傳數值並組成一句報告資料框維度的文字。

所幸,glue 套件是 tidyverse 套件集合的一部分,且在設計時就考量到 data frame,因此我們可以直接對整個欄位運算。譬如,你可以在 mutate() 中使用它,建立一個新欄位,將其他欄位的數值串成一個字串。在這個練習中,你會把這些做法套用到 users 資料框上,該資料框包含其他欄位的數值。

本練習屬於課程

R 中級 Regular Expressions

檢視課程

練習說明

  • 使用 glue() 函式回報 users 的列數與欄數,並分別暫存在變數 nm
  • 檢視 users 資料框,只要執行印出欄位名稱的那一行即可。
  • 以 mutate 產生新欄位 n_logins,使用 namelogins 兩欄來描述每位使用者登入的次數。

動手互動練習

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

# Create two temporary variables "n" and "m" and use them
glue(
  "The data frame 'users' has ___ rows and ___ columns.",
  ___ = nrow(users),
  ___ = ncol(users)
)

# This lists the column names of the data frame users
colnames(users)

# Use them to create a sentence about the numbers of logins
users %>% mutate(
  n_logins = glue("___ logged in ___ times.")
)
編輯並執行程式碼