📜  如何将 CSV 从 URL 读取到 R 中?

📅  最后修改于: 2022-05-13 01:55:09.272000             🧑  作者: Mango

如何将 CSV 从 URL 读取到 R 中?

在本文中,我们将了解如何使用 R 编程语言从 URL 读取 CSV 文件。

方法 1:使用 Base R

这里我们使用 read.csv() 方法,这是 R 编程中的一个内置函数。此函数类似于Python ,因为它读取 CSV 文件并将数据返回到数据框中。

句法:

示例:从 URL 读取 CSV

R
# importing Data
data <- read.csv('https://www.stats.govt.nz/assets/Uploads\
/Annual-enterprise-survey/Annual-enterprise-survey-2020-\
financial-year-provisional/Download-data/annual-enterprise\
-survey-2020-financial-year-provisional-csv.csv')
 
# display top 5 row
head(data)


R
# importing Data
data <- read.fread('https://www.stats.govt.nz/assets/Uploads\
/Annual-enterprise-survey/Annual-enterprise-survey-2020-\
financial-year-provisional/Download-data/annual-enterprise\
-survey-2020-financial-year-provisional-csv.csv')
 
# display top 5 row
head(data)


R
library(data.table)
 
# import data from URL
data <- fread('https://www.stats.govt.nz/assets/Uploads
/Annual-enterprise-survey/Annual-enterprise-survey-2020-
financial-year-provisional/Download-data/annual-enterprise
-survey-2020-financial-year-provisional-csv.csv')
 
# Display first five rows
head(data)


输出:

方法2:使用data.table

这个包能够从 URL 读取数据。基本上 data.table 用于数据操作操作,例如子集、组、更新、连接等。该包包含 fread()函数,该函数将 URL 作为输入以完成工作。

句法:

示例:从 URL 读取 CSV

R

# importing Data
data <- read.fread('https://www.stats.govt.nz/assets/Uploads\
/Annual-enterprise-survey/Annual-enterprise-survey-2020-\
financial-year-provisional/Download-data/annual-enterprise\
-survey-2020-financial-year-provisional-csv.csv')
 
# display top 5 row
head(data)

输出:

示例 2:从 URL 读取 CSV

R

library(data.table)
 
# import data from URL
data <- fread('https://www.stats.govt.nz/assets/Uploads
/Annual-enterprise-survey/Annual-enterprise-survey-2020-
financial-year-provisional/Download-data/annual-enterprise
-survey-2020-financial-year-provisional-csv.csv')
 
# Display first five rows
head(data)

输出: