【R语言 数据处理】R语言数据变形melt用法

1、需要安装的包

install.packages("reshape2")
install.packages("knitr")

2、加载包

rm(list=ls())
gc()
library(reshape2)
library(knitr)

3、创建数据集

data<-data.frame(Name = c("苹果","谷歌","脸书","亚马逊","腾讯"),Company = c("Apple","Google","Facebook","Amozon","Tencent"),Sale2013 = c(5000,3500,2300,2100,3100),Sale2014 = c(5050,3800,2900,2500,3300),Sale2015 = c(5050,4000,3200,2800,3700),Sale2016 = c(6000,4800,4500,3500,4300))

4、变形之前数据展示

kable(data,format="markdown") 
NameCompanySale2013Sale2014Sale2015Sale2016
苹果Apple5000505050506000
谷歌Google3500380040004800
脸书Facebook2300290032004500
亚马逊Amozon2100250028003500
腾讯Tencent3100330037004300

5、melt数据变形

mydata<-melt(data,id.vars=c("Name","Company"),variable.name="Year",value.name="Sale")

6、变形之后数据展示

kable(mydata,format=”markdown”)

NameCompanyYearSale
苹果AppleSale20135000
谷歌GoogleSale20133500
脸书FacebookSale20132300
亚马逊AmozonSale20132100
腾讯TencentSale20133100
苹果AppleSale20145050
谷歌GoogleSale20143800
脸书FacebookSale20142900
亚马逊AmozonSale20142500
腾讯TencentSale20143300
苹果AppleSale20155050
谷歌GoogleSale20154000
脸书FacebookSale20153200
亚马逊AmozonSale20152800
腾讯TencentSale20153700
苹果AppleSale20166000
谷歌GoogleSale20164800
脸书FacebookSale20164500
亚马逊AmozonSale20163500
腾讯TencentSale20164300
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页