week4reshape包

本文介绍了R语言中reshape包的基本使用方法,包括如何融合(melt)和重铸(cast)数据集。通过实例展示了如何利用该包进行数据重构,以便于后续的数据分析和可视化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

reshape包(转载自r实战)

reshape包是一套重构和整合数据集的绝妙的万能工具。由于它的这种万能特性,可能学
起来会有一点难度。我们将慢慢地梳理整个过程,并使用一个小型数据集作为示例,这样每一步
发生了什么就很清晰了。由于reshape包并未包含在R的标准安装中,在第一次使用它之前需要
使用install.packages(“reshape”)进行安装。
大致说来,你需要首先将数据“融合”(melt),以使每一行都是一个唯一的标识符—变量组
合。然后将数据“重铸”(cast)为你想要的任何形状。在重铸过程中,你可以使用任何函数对数
据进行整合。将使用的数据集如表所示。
这里写图片描述

在这个数据集中,测量measurement是指最后两列中的值(5、6、3、5、6、1、2、4)。每
个测量都能够被标识符变量(在本例中,标识符是指IDTime以及观测属于X1还是X2)唯一地确
定。举例来说,在知道ID为1、Time为1,以及属于变量X1之后,即可确定测量值为第一行中的5。

melt融合

数据集的融合是将它重构为这样一种格式:每个测量变量独占一行,行中带有要唯一确定这
个测量所需的标识符变量。要融合表中的数据,可使用以下代码:

library(reshape)
md <- melt(mydata, id=(c("id", "time")))

这里写图片描述

2. cast() 重铸

cast()函数读取已融合的数据,并使用你提供的公式和一个(可选的)用于整合数据的函
数将其重塑。调用格式为:

newdata <- cast(md, formula, FUN)

其中的md为已融合的数据,formula描述了想要的最后结果,而FUN是(可选的)数据整合函数。
其接受的公式.

在这一公式中,rowvar1+ rowvar2+ ...定义了要划掉的变量集合,以确定各行的内容,
colvar1+ colvar2+ ...则定义了要划掉的、确定各列内容的变量集合。参见图5-1中的
示例。

这里写图片描述

reshape包例子

library(reshape2)
dstats<-function(x)(c(n=length(x), mean=mean(x), sd=sd(x)))
# measure.vars 欲分类计算的变量名
# id.vars 变量 
dfm<-melt(mtcars, measure.vars=c("mpg", "hp", "wt"),id.vars=c("am", "cyl"))
dcast(dfm, am + cyl + variable ~., dstats)
> head(dfm)
  am cyl variable value
1  1   6      mpg  21.0
2  1   6      mpg  21.0
3  1   4      mpg  22.8
4  0   6      mpg  21.4
5  0   8      mpg  18.7
6  0   6      mpg  18.1

> cast(dfm, am + cyl + variable ~., dstats)
   am cyl variable  n       mean         sd
1   0   4      mpg  3  22.900000  1.4525839
2   0   4       hp  3  84.666667 19.6553640
3   0   4       wt  3   2.935000  0.4075230
4   0   6      mpg  4  19.125000  1.6317169
5   0   6       hp  4 115.250000  9.1787799
6   0   6       wt  4   3.388750  0.1162164
7   0   8      mpg 12  15.050000  2.7743959
8   0   8       hp 12 194.166667 33.3598379
9   0   8       wt 12   4.104083  0.7683069
这里面的编码:“ self.node_feat_encoder = nn.Sequential( nn.Linear(time_steps, 16), # 将14个时间步编码为特征 nn.ReLU(), nn.Linear(16, node_feat_dim) )”可以换成正余弦编码吗?数据在输入进去的时候,第一列是时间,请帮我加入正余弦编码:“class TimeCovariates(object): """Extract all time covariates except for holidays.""" def __init__( self, datetimes, normalized = True ): """Init function. Args: datetimes: pandas DatetimeIndex (lowest granularity supported is min) normalized: whether to normalize features or not holiday: fetch holiday features or not Returns: None """ self.normalized = normalized self.dti = datetimes def _minute_of_hour(self): minutes = np.array(self.dti.minute, dtype=np.float32) if self.normalized: minutes = minutes / 59.0 - 0.5 return minutes def _hour_of_day(self): hours = np.array(self.dti.hour, dtype=np.float32) if self.normalized: hours = hours / 23.0 - 0.5 return hours def _day_of_week(self): day_week = np.array(self.dti.dayofweek, dtype=np.float32) if self.normalized: day_week = day_week / 6.0 - 0.5 return day_week def _day_of_month(self): day_month = np.array(self.dti.day, dtype=np.float32) if self.normalized: day_month = day_month / 30.0 - 0.5 return day_month def _day_of_year(self): day_year = np.array(self.dti.dayofyear, dtype=np.float32) if self.normalized: day_year = day_year / 364.0 - 0.5 return day_year def _month_of_year(self): month_year = np.array(self.dti.month, dtype=np.float32) if self.normalized: month_year = month_year / 11.0 - 0.5 return month_year def _week_of_year(self): week_year = np.array(self.dti.strftime("%U").astype(int), dtype=np.float32) if self.normalized: week_year = week_year / 51.0 - 0.5 return week_year def get_covariates(self): """Get all time covariates.""" moh = self._minute_of_hour().reshape(1, -1) hod = self._hour_of_day().reshape(1, -1) dom = self._day_of_month().reshape(1, -1) dow = self._day_of_week().reshape(1, -1) doy = self._day_of_year().reshape(1, -1) moy = self._month_of_year().reshape(1, -1) woy = self._week_of_year().reshape(1, -1) all_covs = [ moh, hod, dom, dow, doy, moy, woy, ] columns = ["moh", "hod", "dom", "dow", "doy", "moy", "woy"] return pd.DataFrame( data=np.vstack(all_covs).transpose(), columns=columns, index=self.dti, )”并帮我分析一下这样是否能够提升预测精度?
最新发布
04-06
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值