1

我在 gtrendsR 的帮助下导入了一些谷歌趋势数据并成功绘制了它。现在我希望用 h.clust 对数据进行聚类,但我的问题是我没有成功转换为距离向量的数据格式。

数据如下所示:

datestart, date-end, trend1, trend2, trend3 
1   2004-01-04 2004-01-10     57    18     39 
2   2004-01-11 2004-01-17     55    17     39 
3   2004-01-18 2004-01-24     56    20     43 
4   2004-01-25 2004-01-31     55    19     41 
5   2004-02-01 2004-02-07     57    20     39 
6   2004-02-08 2004-02-14     57    18     40 

为了绘制数据,我使用了 data.frame。

谁能帮我解决如何转换数据的想法,以便我可以将趋势的“形状”聚集到不同的集群中?

4

1 回答 1

1

您可以对 Gmail 趋势曲线的形状进行聚类,如下所示:

set.seed(1)
library(gtrendsR)
library(dtw)

# Switch https://www.google.com/settings/security/lesssecureapps to on if needed:
gconnect("your_google_email", "your_google_psw")
cotton_trend <- gtrends(c("cotton", "satin", "velvet"), res="week")
d <- dist(t(cotton_trend$trend[, -(1:2)]), method="DTW")
hc <- hclust(d)

# plot the results
par(mfrow=c(1,2))
plot(cotton~end, cotton_trend$trend, type="l", ylim=range(cotton_trend$trend[, -(1:2)]), col=3, ylim="")
for (x in 4:ncol(cotton_trend$trend)) lines(x=cotton_trend$trend$end, y=cotton_trend$trend[, x], col=x)
legend("topleft", names(cotton_trend$trend)[-(1:2)], lty=1, col=3:ncol(cotton_trend$trend))
plot(hc)
rect.hclust(hc, k=2)

# extract clusters: 
cutree(hc, k=2)
# cotton  satin velvet 
#      1      2      1 

在此处输入图像描述

于 2016-02-05T15:21:59.487 回答