開始使用免費開始

存取 sp 物件中的資料

你不太可能剛好知道要保留哪些元素的索引,更常見的情況是根據資料屬性來篩選子集。你已經看到與 Spatial___DataFrame 相關的資料會放在 data 欄位(slot)裡,但通常不會直接存取這個欄位。

相反地,在 Spatial___DataFrame 上使用 $ 與 [[ 來做子集,可以直接從其中的 data frame 取出欄位。也就是說,如果 x 是 Spatial___DataFrame 物件,那 x$col_name 或 x[["col_name"]] 會直接取得 data frame 裡的 col_name 欄位。把這想成一個捷徑;你不必先到 data 欄位裡再從物件取出正確的欄(例如 x@data$col_name),改用 x$col_name 就能達成。

先來確認 data 欄位中的物件就是一般的 data frame,接著練習如何取出欄位。

本練習屬於課程

在 R 視覺化地理空間資料

檢視課程

練習說明

  • 針對 countries_spdf 的 data 欄位(slot)分別呼叫 head() 與 str()(一次一個)。「確認這個物件就是一般的 data frame」。
  • 使用 $ 取出 countries_spdf 的 name 欄位。
  • 使用 [[ 取出 countries_spdf 的 subregion 欄位。

動手互動練習

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

# Call head() and str() on the data slot of countries_spdf



# Pull out the name column using $


# Pull out the subregion column using [[
編輯並執行程式碼