library(dplyr)
library(tidyr)
library(writexl)
application <- read.csv("data/application_sample.csv")
head(application)
tail(application, 10)
head(application, 10)
NA
arrange(application, AMT_INCOME_TOTAL)
arrange(application, CODE_GENDER, AMT_CREDIT)
str(data): cấu trúc của dataset, cung cấp thông
tin:
Số dòng số cột
Tên các cột, kiểu dữ liệu của từng cột
Một số data đầu tiên của cột
str(application)
'data.frame': 20000 obs. of 11 variables:
$ SK_ID_CURR : int 411019 360800 238560 130181 216974 128257 205326 160384 317054 369746 ...
$ TARGET : int 0 0 0 0 0 0 1 0 0 0 ...
$ NAME_CONTRACT_TYPE: chr "Cash loans" "Revolving loans" "Cash loans" "Cash loans" ...
$ CODE_GENDER : chr "F" "F" "M" "M" ...
$ FLAG_OWN_CAR : chr "N" "N" "N" "N" ...
$ FLAG_OWN_REALTY : chr "Y" "Y" "Y" "N" ...
$ CNT_CHILDREN : int 0 1 1 1 0 1 3 0 0 0 ...
$ CNT_FAM_MEMBERS : int 1 2 2 3 1 3 5 2 1 1 ...
$ AMT_INCOME_TOTAL : num 180000 94500 157500 157500 202500 ...
$ AMT_CREDIT : num 675000 180000 675000 746280 961146 ...
$ NAME_FAMILY_STATUS: chr "Single / not married" "Single / not married" "Separated" "Married" ...
dim(data): Số dòng và số cột của bảng
dim(application)
[1] 20000 11
nrow(data): số dòng (số quan sát) của
bảng
nrow(application)
[1] 20000
ncol(data): số cột (số biến) của
bảng
ncol(application)
[1] 11
summary(data): thống kê mô tả nhanh các
biến
summary(application)
SK_ID_CURR TARGET NAME_CONTRACT_TYPE CODE_GENDER FLAG_OWN_CAR FLAG_OWN_REALTY CNT_CHILDREN
Min. :100031 Min. :0.0000 Length:20000 Length:20000 Length:20000 Length:20000 Min. : 0.0000
1st Qu.:187757 1st Qu.:0.0000 Class :character Class :character Class :character Class :character 1st Qu.: 0.0000
Median :276387 Median :0.0000 Mode :character Mode :character Mode :character Mode :character Median : 0.0000
Mean :277116 Mean :0.0774 Mean : 0.4153
3rd Qu.:366167 3rd Qu.:0.0000 3rd Qu.: 1.0000
Max. :456238 Max. :1.0000 Max. :12.0000
CNT_FAM_MEMBERS AMT_INCOME_TOTAL AMT_CREDIT NAME_FAMILY_STATUS
Min. : 1.000 Min. : 27000 Min. : 45000 Length:20000
1st Qu.: 2.000 1st Qu.: 112500 1st Qu.: 270000 Class :character
Median : 2.000 Median : 148500 Median : 512064 Mode :character
Mean : 2.152 Mean : 170469 Mean : 599440
3rd Qu.: 3.000 3rd Qu.: 202500 3rd Qu.: 808650
Max. :14.000 Max. :18000090 Max. :3375000
NA's :1
dplyrdplyr là một thư viện có chức năng thao
tác và biến đổi dữ liệu một cách trực quan. Package dplyr cung cấp những
function hoán chuyển và thao tác trên dữ liệu sau khi nó đã được tải vào
R.
filter(): lọc dữ liệuLọc những khoản vay có thu nhập >= 100.000 USD
head(
filter(application, AMT_INCOME_TOTAL >= 100000)
)
Đếm số khoản vay mà người đi vay có thu nhập >= 100.000 USD
nrow(
filter(application, AMT_INCOME_TOTAL >= 100000)
)
[1] 15873
distinct(): bỏ quan sát trùng**Số lượng quan sát ban đầu chưa bỏ trùng là 20000
nrow(application)
[1] 20000
Sau khi thực hiện bỏ quan sát trùng thì số quan sát không thay đổi, do đó dataset này không có quan sát trùng
nrow(distinct(application, SK_ID_CURR))
[1] 20000
Có thể dùng distinct(data, tên cột) để kiểm tra số lượng
biểu hiện có trong cột đó, ví dụ cột CODE_GENDER chỉ có 2
biểu hiện là M và F
distinct(application, CODE_GENDER)
arrange(): sắp xếp dữ liệuSắp xếp quan sát theo thứ tự tăng dần của thu nhập
head(
arrange(application, AMT_INCOME_TOTAL),
10
)
Sắp xếp quan sát theo thứ tự giảm dần của thu nhập
head(
arrange(application, desc(AMT_INCOME_TOTAL)),
10
)
Lưu ý: trường hợp dữ liệu bị khuyết (missing data
- NA) thì dù sắp xếp tăng dần hay giảm dần thì giá trị
khuyết luôn được đưa xuống cuối cùng của bảng
select()data1 <- select(application, CODE_GENDER, AMT_INCOME_TOTAL, AMT_CREDIT)
head(data1)
select(application, CODE_GENDER, AMT_INCOME_TOTAL, AMT_CREDIT)
Lấy từ cột A đến cột B: CỘT A : CỘT B
select(application, TARGET : AMT_CREDIT)
Dùng dấu - để bỏ đi cột không cần lấy
select(application, -SK_ID_CURR, -TARGET, -CODE_GENDER)
head(select(application, -SK_ID_CURR, -TARGET, -CODE_GENDER))
Ví dụ đặt tên cột bắt đầu bằng chữ q:
select(application, starts_with('C'))
select(application, ends_with('DER'))
Đổi tên cột CODE_GENDER -> gender
Đổi tên cột SK_ID_CURR -> id
rename(application, gender = CODE_GENDER,
id = SK_ID_CURR,
car = FLAG_OWN_CAR,
income= AMT_INCOME_TOTAL,
n_children= CNT_CHILDREN,
credit=AMT_CREDIT,
n_fam_members= CNT_FAM_MEMBERS,
fam_status = NAME_FAMILY_STATUS,
contract_type = NAME_CONTRACT_TYPE
)
Đổi đơn vị
mutate(application,
income2 = AMT_INCOME_TOTAL / 1000)
Muốn sửa đổi cột có trong bảng (AMT_INCOME_TOTAL)
#TARGET = as.character(TARGET)
mutate(application,
AMT_INCOME_TOTAL = AMT_INCOME_TOTAL/1000,
AMT_CREDIT = AMT_CREDIT/1000)
Chia khách hàng thành ba nhóm, thu nhập cao, trung bình, thấp
min(application$AMT_INCOME_TOTAL)
[1] 27000
max(application$AMT_INCOME_TOTAL)
[1] 18000090
mean(application$AMT_INCOME_TOTAL) #tính trung bình
[1] 170468.9
median(application$AMT_INCOME_TOTAL) #trung vị
[1] 148500
quantile(application$AMT_INCOME_TOTAL, 0.25) #phân vị mức 25
25%
112500
var(application$AMT_INCOME_TOTAL) #phương sai
[1] 35193056111
sd(application$AMT_INCOME_TOTAL) # độ lệch chuẩn
[1] 187598.1
Chia làm 3 nhóm
Thấp: < 100.000
Trung bình: 100.000 - 500.000
Cao: > 500.000
mutate(
application,
income_class = case_when(
AMT_INCOME_TOTAL < 100000 ~ "Thấp",
AMT_INCOME_TOTAL >=100000 & AMT_INCOME_TOTAL < 500000 ~ "Trung bình",
AMT_INCOME_TOTAL >= 500000 ~ "Cao",
TRUE ~ "Không xác định" #những trường hợp còn lại, phải để dòng TRUE ở cuối
)
)
mutate(
application,
AMT_INCOME_TOTAL = AMT_INCOME_TOTAL/1000,
have_child= case_when (
CNT_CHILDREN > 0 ~ TRUE,
CNT_CHILDREN == 0 ~ FALSE
)
)
Chia thu nhập
0 - 100%
25%: Thấp
25%-75%: Trung bình
75%: Cao
mutate(application,
income_class = case_when(
AMT_INCOME_TOTAL < quantile (application$AMT_INCOME_TOTAL, 0.25) ~ "Thấp",
AMT_INCOME_TOTAL < quantile (application$AMT_INCOME_TOTAL, 0.75) ~ "Trung bình",
AMT_INCOME_TOTAL >= quantile (application$AMT_INCOME_TOTAL, 0.75) ~ "Cao"
))
Tổng hợp dữ liệu, tạo bảng thống kê mô tả
summarize(
application,
obs = n(), #tính số quan sát
mean_income = mean(AMT_INCOME_TOTAL),
var_income = var(AMT_INCOME_TOTAL),
sd_income = sd(AMT_INCOME_TOTAL),
q1 = quantile(AMT_INCOME_TOTAL, 0.25),
q3 = quantile(AMT_INCOME_TOTAL, 0.75),
median = median(AMT_INCOME_TOTAL)
)
as.data.frame(
t( summarize( application,
obs = n(), #tính số quan sát
mean_income = mean(AMT_INCOME_TOTAL),
var_income = var(AMT_INCOME_TOTAL),
sd_income = sd(AMT_INCOME_TOTAL),
q1 = quantile(AMT_INCOME_TOTAL, 0.25),
q3 = quantile(AMT_INCOME_TOTAL, 0.75),
median = median(AMT_INCOME_TOTAL)
)
)
)
NA
Toán tử vipe: #%>%
options(scipen = 999) #tắt hiển thị science number
summarize(
application,
obs = n(), #tính số quan sát
mean_income = mean(AMT_INCOME_TOTAL),
var_income = var(AMT_INCOME_TOTAL),
sd_income = sd(AMT_INCOME_TOTAL),
q1 = quantile(AMT_INCOME_TOTAL, 0.25),
q3 = quantile(AMT_INCOME_TOTAL, 0.75),
median = median(AMT_INCOME_TOTAL)
) %>%
t() %>%
as.data.frame() %>%
rename(income = V1) %>%
write_xlsx('desc.xlsx')
options(scipen = 999) #tắt hiển thị science number
summarize(
application,
obs = n(), #tính số quan sát
mean_income = mean(AMT_INCOME_TOTAL),
var_income = var(AMT_INCOME_TOTAL),
sd_income = sd(AMT_INCOME_TOTAL),
q1 = quantile(AMT_INCOME_TOTAL, 0.25),
q3 = quantile(AMT_INCOME_TOTAL, 0.75),
median = median(AMT_INCOME_TOTAL)
) %>%
t() %>%
as.data.frame() %>%
rename(income = V1) %>%
mutate(
info = rownames(.)
)%>%
select(info, income) %>%
write_xlsx('desc2.xlsx')
Group by()
group_by(application, CODE_GENDER) %>%
summarize(
obs = n(),
mean_income = mean (AMT_INCOME_TOTAL),
sd_income = sd(AMT_INCOME_TOTAL)
) %>%
rename(
gender = CODE_GENDER
)
tidyrhead(application, 10) %>%
select(SK_ID_CURR, CODE_GENDER, AMT_CREDIT, AMT_INCOME_TOTAL) %>%
gather(CODE_GENDER, AMT_CREDIT, AMT_INCOME_TOTAL,
key = "var",
value = "value"
)%>%
write_xlsx('ID')
Sử dụng data GDP
gdp <- read.csv("data/gdp.csv")
pop <- read.csv("data/pop.csv")
Error in exists(cacheKey, where = .rs.WorkingDataEnv, inherits = FALSE) :
invalid first argument
Error in assign(cacheKey, frame, .rs.CachedDataEnv) :
attempt to use zero-length variable name
head(gdp)
#lấy từ năm (cột) x1960 tới x2021
gdp <-gather(gdp, X1960 : X2021, key="Year", value="GDP")%>%
mutate(
Year= as.numeric(gsub("X", "", Year))
)
#không dùng định danh khi reshape
head(pop)
pop1<- gather(pop, X1960:X2021, key= "Year", value = "Population")%>%
mutate(
Year = as.numeric(gsub("X","",Year))
)
spread(pop1, key= Year, value= Population) %>%
head()
full_join, inner_join, left_join, right_join
select(gdp, -Country.Name) %>%
full_join(pop1, by= c("Country.Code", "Year")) %>%
select(Country.Name, everything())
#đưa cột Country Name lên đầu
# everything là những cột còn lại
cbind()
#income
summarise(
application,
mean = mean (AMT_INCOME_TOTAL),
sd = sd (AMT_INCOME_TOTAL),
q1= quantile(AMT_INCOME_TOTAL, 0.25),
q3= quantile(AMT_INCOME_TOTAL, 0.75),
median= median(AMT_INCOME_TOTAL),
min = min(AMT_INCOME_TOTAL),
max = max(AMT_INCOME_TOTAL)
)
#income
desc.income <- summarise(
application,
mean = mean (AMT_INCOME_TOTAL),
sd = sd (AMT_INCOME_TOTAL),
q1= quantile(AMT_INCOME_TOTAL, 0.25),
q3= quantile(AMT_INCOME_TOTAL, 0.75),
median= median(AMT_INCOME_TOTAL),
min = min(AMT_INCOME_TOTAL),
max = max(AMT_INCOME_TOTAL)
) %>%
t() %>%
as.data.frame() %>%
rename(income = V1)
desc.income
#income
desc.credit <- summarise(
application,
mean = mean (AMT_CREDIT),
sd = sd (AMT_CREDIT),
q1= quantile(AMT_CREDIT, 0.25),
q3= quantile(AMT_CREDIT, 0.75),
median= median(AMT_CREDIT),
min = min(AMT_CREDIT),
max = max(AMT_CREDIT)
) %>%
t() %>%
as.data.frame() %>%
rename(credit = V1)
desc.credit
cbind(desc.income, desc.credit)
rbind()
data1 <- data.frame(
x = c(1,2),
y = c(3,4)
)
data1
data2 <- data.frame(
x = c(5,6),
y = c(7,8)
)
data2
rbind(data1, data2)