如何在R中重新构造数据帧
我有以下建议:如何在R中重新构造数据帧,r,pivot,reshape2,R,Pivot,Reshape2,我有以下建议: >df cluster_no days_to_port channel 1 1 2.8 MMR 2 2 4.1 Spark Retail Stores 3 3 2.4 Spark Retail Stores 4 4 3.0 Spark Retail Stores 5
>df
cluster_no days_to_port channel
1 1 2.8 MMR
2 2 4.1 Spark Retail Stores
3 3 2.4 Spark Retail Stores
4 4 3.0 Spark Retail Stores
5 5 3.5 Spark Retail Stores
channel_outlet_name region
1 PIN Distributor Ltd (Activata) Auckland - Central
2 Spark - Auckland Int Airport Mangere
3 Spark - Auckland Int Airport Mangere
4 Spark - Auckland Int Airport Mangere
5 Spark - Auckland Int Airport Mangere
我正在尝试将其重新塑造/转换为以下格式,以便我可以进行进一步的条件格式设置和分析:(因此列是集群编号,行是变量)
我可以在excel中使用pivot实现:
我想用R实现同样的效果(顺便说一句,df中的数值是平均值,分类值是模式)df%
排列(簇、值)
出来
关键1 2 3 4 5
1渠道MMR Spark零售店Spark零售店Spark零售店Spark零售店Spark零售店
2频道插座名称销分销商有限公司(Activata)Spark-奥克兰国际机场Spark-奥克兰国际机场Spark-奥克兰国际机场Spark-奥克兰国际机场Spark-奥克兰国际机场Spark
3天到港口2.8 4.1 2.4 3.5
4奥克兰地区-中央曼格雷曼格雷曼格雷曼格雷
预期输出中的值是什么?t(df)虽然这不会维护变量的类,但它并没有提供我想要的结构。太棒了。这就是我想要的。
cluster_no 1 2 3 4 5
days_to_port
channel
channel_outlet_name
region
df <- data.frame(cluster=1:5,
days_to_port=c(2.8,4.1,2.4,3.0,3.5),
channel=c('MMR','Spark Retail Stores','Spark Retail Stores','Spark Retail Stores','Spark Retail Stores'),
channel_outlet_name=c('PIN Distributor Ltd (Activata)','Spark - Auckland Int Airport','Spark - Auckland Int Airport','Spark - Auckland Int Airport','Spark - Auckland Int Airport'),
region=c('Auckland - Central','Mangere','Mangere','Mangere','Mangere'))
library(tidyr)
out <- df %>% gather(key=key,value=value,-cluster) %>%
spread(cluster,value)
out
key 1 2 3 4 5
1 channel MMR Spark Retail Stores Spark Retail Stores Spark Retail Stores Spark Retail Stores
2 channel_outlet_name PIN Distributor Ltd (Activata) Spark - Auckland Int Airport Spark - Auckland Int Airport Spark - Auckland Int Airport Spark - Auckland Int Airport
3 days_to_port 2.8 4.1 2.4 3 3.5
4 region Auckland - Central Mangere Mangere Mangere Mangere