開始使用免費開始

計算並繪製兩名球員之間的距離

你已經取得一場足球比賽中,兩名球員相對於球場中心的座標,想要計算他們之間的距離。

在這個練習中,你會先繪製兩名球員的位置,並使用歐式距離公式手動計算他們之間的距離。

本練習屬於課程

R 的叢集分析

檢視課程

練習說明

  • 使用 ggplottwo_players 資料框繪製他們的位置。
  • 將兩名球員的位置各自擷取成兩個資料框 player1player2
  • 使用歐式距離公式 $$\sqrt{(x_1-x_2)^2+(y_1-y_2)^2}$$ 計算 player1 與 player2 之間的距離。

動手互動練習

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

# Plot the positions of the players
ggplot(___, aes(x = ___, y = ___)) + 
  geom_point() +
  # Assuming a 40x60 field
  lims(x = c(-30,30), y = c(-20, 20))

# Split the players data frame into two observations
player1 <- two_players[___, ]
player2 <- two_players[___, ]

# Calculate and print their distance using the Euclidean Distance formula
player_distance <- sqrt( (player1$___ - player2$___)^2 + (player1$___ - player2$___)^2 )
player_distance
編輯並執行程式碼