美文网首页
R中高级数据

R中高级数据

作者: 蓝色滑行 | 来源:发表于2018-12-09 15:46 被阅读0次

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 博士

相关文章

  • R中高级数据

    1.拆分聚合列 setwd("D:/《用商业案例学R语言数据挖掘》教材代码及数据/data") #设置工作路径d...

  • 生信学习小组Day5笔记-lamyusam_

    R语言学习 今天,了解了R中的数据类型,初步学习R语言的数据结构。 R的数据类型 向量(vector) R语言中的...

  • day5 阿来

    继续学习R语言 R语言数据学习 数据R语言学习.png 数据输入 数据输出 总结 R语言学习的第二天,熟悉了很多操...

  • R语言基础--数据类型-总结

    R语言基础--数据类型-总结 1、R语言基础--数据类型之向量 2、R语言基础--数据类型之因子 3、R语言基础-...

  • R基础快速入门(4)

    文集地址 R语言快速入门 R语言数据重塑 *R中的数据重整是关于将数据组织成行和列的方式。 R中的大多数时间数据处...

  • 标哥笔试面试

    iOS中高级笔试题一iOS中高级笔试题二

  • 【R数据科学读书笔记】R语言的数据结构原来可以这样理解

    R语言的数据结构原来可以这样理解 这是R数据科学的读书笔记之一,《R数据科学》是一本教你如何用R语言进行数据分析的...

  • 利用rwda包抓取微博评论并分析

    工具:Rstudio,R(3.3.4) 参考文章: R微博数据分析 用R爬取微博评论数据

  • R(1)

    R作为计算器 R中的数据包 许多数据集[https://stat.ethz.ch/R-manual/R-devel...

  • R学习笔记:内置数据集

    R内置数据集 在学习R和做练习的过程中,经常用到内置数据集。R的内置数据集一共有两种: R内部 datasets ...

网友评论

      本文标题:R中高级数据

      本文链接:https://www.haomeiwen.com/subject/xktkhqtx.html