In [1]:
install.packages('readxl')


Installing package into ‘/home/duyetdev/R/x86_64-pc-linux-gnu-library/3.3’
(as ‘lib’ is unspecified)

In [2]:
library(readxl)

Xử lý với file exel trong R

Sử dụng package readxl để đọc file urbanpop.xlsx

  • excel_sheets(): liệt kê danh sách sheet
  • read_excel(): import excel to data.frame.

In [4]:
# Liệt kê danh sách các sheet với hàm excel_sheets()
sheets <- excel_sheets("urbanpop.xlsx")
sheets


  1. '1960-1966'
  2. '1967-1974'
  3. '1975-2011'

In [7]:
data <- read_excel("urbanpop.xlsx", sheet = '1960-1966')
head(data)


country1960196119621963196419651966
Afghanistan 769308 814923.049 858521.698 903913.86 951225.94 1000582.35 1058743.47
Albania 494443 511802.780 529438.851 547376.75 565571.75 583982.89 602512.17
Algeria 3293999 3515147.548 3739963.007 3973289.13 4220987.01 4488175.64 4649105.24
American Samoa NA 13660.298 14165.797 14758.93 15396.42 16044.82 16693.11
Andorra NA 8723.921 9700.346 10748.38 11865.86 13052.75 14216.81
Angola 521205 548265.046 579695.370 612086.70 645261.59 679109.12 717833.40

In [8]:
data <- read_excel("urbanpop.xlsx", sheet = 2) # Đọc sheet 2
head(data)


country19671968196919701971197219731974
Afghanistan 1119067.20 1182159.06 1248900.79 1319848.78 1409001.09 1502401.79 1598835.45 1696444.83
Albania 621179.85 639964.46 658853.12 677839.12 698932.25 720206.57 741681.04 763385.45
Algeria 4826104.22 5017298.60 5219331.87 5429743.08 5619041.53 5815734.49 6020647.35 6235114.38
American Samoa 17348.66 17995.51 18618.68 19206.39 19752.02 20262.67 20741.97 21194.38
Andorra 15439.62 16726.99 18088.32 19528.96 20928.73 22405.84 23937.05 25481.98
Angola 757496.32 798459.26 841261.96 886401.63 955010.09 1027397.35 1103829.78 1184486.23

Đọc tất cả sheet


In [9]:
my_workbook <- lapply(excel_sheets("urbanpop.xlsx"),
                      read_excel,
                      path = "urbanpop.xlsx")

In [ ]:
my_workbook

In [ ]: