R语言中文件的读写

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)

 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值