對資料做對應運算(Mapping your data)
搭配 mutate(),你可以使用 map() 將運算結果附加到資料框中。由於 map() 一律回傳清單的向量,你必須使用 unnest(),把結果展開成數值向量。
在這裡,你會透過計算 gapminder 資料集各國的人口平均值來練習這個功能。
本練習屬於課程
Tidyverse 的 Machine Learning
練習說明
- 使用
map()套用mean(),計算每個國家的人口平均值,並用mutate()新增名為mean_pop的清單欄位。 - 檢視
pop_nested的前 6 列。 - 使用
unnest()將mean_pop清單轉成數值欄,並將結果存為資料框pop_mean。 - 使用
head()檢視pop_mean。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Calculate the mean population for each country
pop_nested <- gap_nested %>%
mutate(mean_pop = map(___, ~mean(.x$___)))
# Take a look at pop_nested
head(___)
# Extract the mean_pop value by using unnest
pop_mean <- pop_nested %>%
unnest(___)
# Take a look at pop_mean
head(___)