在R语言中,如何读入案例中的数据?
时间: 2024-10-23 14:13:31 浏览: 28
在R语言中,读取数据通常有几种常见的方式,取决于数据的源。以下是几种常见的数据导入方法:
1. **从CSV文件**:如果你的数据存储在一个.csv文件里,可以使用`read.csv()`函数,例如:
```
data <- read.csv("file_name.csv")
```
如果文件不在当前工作目录下,需要提供完整的文件路径。
2. **从Excel文件**:对于.xlsx文件,可以使用`readxl`包,如:
```R
library(readxl)
data <- read_excel("file_name.xlsx")
```
需先安装`readxl`包:`install.packages("readxl")`.
3. **从数据库**:如果数据来自数据库,可以使用`dbGetQuery()`函数,假设数据库是SQLite:
```R
library(DBI)
con <- dbConnect(RSQLite::SQLite(), "path/to/database.db")
data <- dbGetQuery(con, "SELECT * FROM table_name")
```
4. **从文本文件**(如.txt或.delim):
```R
data <- read.table("file_name.txt", header = TRUE) # 假设第一行是列名
```
5. **从URL**:可以使用`readLines()`获取纯文本数据,或`httr`包下载并处理HTML/JSON等结构化数据。
在操作数据之前,记得检查是否已经成功读取,可以通过查看前几行(`head(data)` 或 `str(data)`)来确认。
阅读全文
相关推荐


















