R data manipulateRR 语言作图

R读取excel文件的最佳方式

2021-11-16  本文已影响0人  小洁忘了怎么分身

背景

众所周知,excel生成的文件后缀是xls或者xlsx,早期读取这样的文件,要么就另存为csv格式,要么就用readxls或者xlsx这样的R包,可能会遇到Rjava报错的问题。现在有了一个优秀的解决办法,就是rio包。

1.编数据

它能够兼容含有多个工作簿的xlsx文件,非常巴适。

用R语言的内置数据组个列表。

l = list(iris = head(iris),
         ToothGrowth = head(ToothGrowth))
l
## $iris
##   Sepal.Length Sepal.Width Petal.Length Petal.Width
## 1          5.1         3.5          1.4         0.2
## 2          4.9         3.0          1.4         0.2
## 3          4.7         3.2          1.3         0.2
## 4          4.6         3.1          1.5         0.2
## 5          5.0         3.6          1.4         0.2
## 6          5.4         3.9          1.7         0.4
##   Species
## 1  setosa
## 2  setosa
## 3  setosa
## 4  setosa
## 5  setosa
## 6  setosa
## 
## $ToothGrowth
##    len supp dose
## 1  4.2   VC  0.5
## 2 11.5   VC  0.5
## 3  7.3   VC  0.5
## 4  5.8   VC  0.5
## 5  6.4   VC  0.5
## 6 10.0   VC  0.5

2.将包含多个数据框的列表导出为xlsx

它就变成了含有多个工作簿的电子表格哦。

library(rio)
export(l,file = "test.xlsx",overwrite = T)

3.将含有多个工作簿的电子表格读入到R语言

有import函数可以读取各种类型的文件,但对于xlsx它只识别第一个工作簿。用import_list读取即可

l2 = import("test.xlsx")
l2
##   Sepal.Length Sepal.Width Petal.Length Petal.Width
## 1          5.1         3.5          1.4         0.2
## 2          4.9         3.0          1.4         0.2
## 3          4.7         3.2          1.3         0.2
## 4          4.6         3.1          1.5         0.2
## 5          5.0         3.6          1.4         0.2
## 6          5.4         3.9          1.7         0.4
##   Species
## 1  setosa
## 2  setosa
## 3  setosa
## 4  setosa
## 5  setosa
## 6  setosa
l3 = import_list("test.xlsx")
l3
## $iris
##   Sepal.Length Sepal.Width Petal.Length Petal.Width
## 1          5.1         3.5          1.4         0.2
## 2          4.9         3.0          1.4         0.2
## 3          4.7         3.2          1.3         0.2
## 4          4.6         3.1          1.5         0.2
## 5          5.0         3.6          1.4         0.2
## 6          5.4         3.9          1.7         0.4
##   Species
## 1  setosa
## 2  setosa
## 3  setosa
## 4  setosa
## 5  setosa
## 6  setosa
## 
## $ToothGrowth
##    len supp dose
## 1  4.2   VC  0.5
## 2 11.5   VC  0.5
## 3  7.3   VC  0.5
## 4  5.8   VC  0.5
## 5  6.4   VC  0.5
## 6 10.0   VC  0.5
上一篇 下一篇

猜你喜欢

热点阅读