1.拆分聚合列
setwd("D:/《用商业案例学R语言数据挖掘》教材代码及数据/data") #设置工作路径
dcast01<- read.csv("dcast01.csv") #读入数据
library(reshape2) #安装reshape2包,需要使用包提供的dcast函数和acast函数拆分列
dcast01
cust_id type monetary #将数据文件按照type类型进行分拆
1 10001 normal 3608
2 10001 special_offer 420
3 10002 normal 1894
4 10003 normal 3503
5 10003 special_offer 156
6 10004 normal 2979
7 10004 special_offer 373
8 10005 normal 2368
9 10006 normal 2534
10 10006 special_offer 58
dcast01_w <- dcast(dcast01,cust_id~type,value.var ='monetary') #将数据拆分为normal和special_offer两列
dcast01_w
cust_id normal special_offer
1 10001 3608 420
2 10002 1894 NA
3 10003 3503 156
4 10004 2979 373
5 10005 2368 NA
6 10006 2534 58
dcast02_w <- dcast(dcast01,cust_id~type,fun.aggregate = length,value.var = 'monetary')#根据客户支付类型计数并拆分两列
dcast02_w
cust_id normal special_offer
1 10001 1 1
2 10002 1 0
3 10003 1 1
4 10004 1 1
5 10005 1 0
6 10006 1 1
2.堆叠列
堆叠是拆分的反向操作,当列表中有多个数值变量时,可以通过堆叠列将多列数据堆积成一列。
dcast01_w_r <- melt(dcast01_w,id.vars = "cust_id",measure.vars = c('normal','special_offer'),variable.name = "type",na.rm = F,value.name = "monetary") #使用melt函数堆叠,其中id.vars为标识列的列名,measure.vars为需要堆叠列名向量,variable.name为堆叠类别变量名称,na.rm是否删除堆叠后数值列产生缺失值的行。
dcast01_w_r
cust_id type monetary
1 10001 normal 3608
2 10002 normal 1894
3 10003 normal 3503
4 10004 normal 2979
5 10005 normal 2368
6 10006 normal 2534
7 10001 special_offer 420
8 10002 special_offer NA
9 10003 special_offer 156
10 10004 special_offer 373
11 10005 special_offer NA
12 10006 special_offer 58
3.分割列
使用tidyr包中的separate函数分割列。
separate(data,col,into,sep =''",remove = TRUE) #into指定分割后变量名向量,remove是否保留原分割变量
info <- read.csv("info.csv")
info
id info
1 1 张三—26-高中
2 2 李四-27-大学
3 3 王五-33-博士
install.packages("tidyr", lib="C:/Program Files/R/R-3.5.1/library")
also installing the dependency ‘rlang’
library(tidyr)
separate(info,col ='info',sep ='-',remove=F,into = c('name','age','edu'))
id info name age edu
1 1 张三—26-高中 张三 26 高中
2 2 李四-27-大学 李四 27 大学
3 3 王五-33-博士 王五 33 博士
网友评论