reshape2::melt/dcast
tidyr::gather/spread
mydata<-data.frame(
Name = c("苹果","谷歌","脸书","亚马逊","腾讯"),
Conpany = c("Apple","Google","Facebook","Amozon","Tencent"),
Sale2013 = c(5000,3500,2300,2100,3100),
Sale2014 = c(5050,3800,2900,2500,3300),
Sale2015 = c(5050,3800,2900,2500,3300),
Sale2016 = c(5050,3800,2900,2500,3300)
)
宽转长
mydata<-melt(
mydata, #待转换的数据集名称
id.vars=c("Conpany","Name"), #要保留的主字段
variable.name="Year", #转换后的分类字段名称(维度)
value.name="Sale" #转换后的度量值名称
)
data1<-gather(
data=mydata, #待转换的数据集名称
key="Year", #转换后的分类字段名称(维度)
value="Sale" , #转换后的度量值名称
Sale2013:Sale2016 #选择将要被拉长的字段组合
) #(可以使用x:y的格式选择连续列,也可以以-z的格式排除主字段)
更多参考https://www.cnblogs.com/zlslch/p/8644627.html
网友评论