1. JSON文件:
library(jsonlite)
file <- "/Users/abcd/Documents/diff_files/json/test.json"
json1 <- read_json(path = file)
write_json(json1, path = file)
2. YAML文件:
library(yaml)
file <- "/Users/abcd/Documents/diff_files/yaml/test.yaml"
write_yaml(data.frame(a = 1:10, b = letters[1:10], c= 11:20), path = file)
read_yaml(file = file)
3. CSV文件:
path1 <- "/Users/abcd/Documents/diff_files/csv/test5.txt"
write.table(file = path1,
x = data.frame(id = 1:(26e4), name = rep(letters, times = 1e4)),
row.name = FALSE, col.names = TRUE, append = FALSE, sep = "\t")
subset1 <- read.table(file = path1, sep = "\t", header = TRUE)
# 读取全部数据
subset2 <- read.table(file = path1, sep = "\t",
skip = 15, header = FALSE)
# 从第16行开始读取
subset3 <- read.table(file = path1, sep = "\t",
skip = 15, nrow = 26, header = FALSE)
# 从第16行开始读取,读取26行
subset4 <- read.table(file = path1, sep = "\t",
skip = 16, nrows = 26,
colClasses = c("integer", "character"))
# 从第16行开始读取,读取26行,指定每列的类型,提高读取速度
4. 使用readLines控制读取行数:
path1 <- "/Users/abcd/Documents/diff_files/csv/test5.txt"
con1 <- file(description = path1, open = "r")
data1 <- readLines(con = con1, n = 1e5)
close(con1)
length(data1)
5. Excel文件读写:
library(readxl)
library(writexl)
path1 <- "/Users/abcd/Documents/diff_files/xlsx/test6.xlsx"
write_xlsx(path = path1,
x = data.frame(id = 1:26e4,
names = rep(LETTERS, times = 1e4)),
col_names = TRUE)
#读取前1000行数据
test6_data1 <- read_xlsx(path = path1,
sheet = 1,
n_max = 1000)
#读取A1到B53的数据
test6_data2 <- read_xlsx(path = path1, sheet = 1,
range = c("A1:B53"))
head(test6_data2)
tail(test6_data2)