如何在R中基于pam聚类结果拆分时间序列数据框
Got it, let's break down how to pull out just the first cluster's time series from your dataframe. I'll cover the most common scenarios you might be working with:
Step 1: Confirm Your Clustering Output
First, make sure you have your PAM clustering result saved as an object (let's call it pam_result for this example). The cluster labels for each of your 157 time series are stored in pam_result$clustering—this is a vector where each value corresponds to the cluster number for the matching row (or column) in your dataframe.
Step 2: Extract Cluster 1 Data
Scenario 1: Time series are stored as rows (each row = 1 day)
If your original dataframe (ts_df) has each time series as a row, use logical indexing to filter rows where the cluster label equals 1:
# Load the cluster package if you haven't already library(cluster) # Assuming you've already run PAM (replace k with your actual number of clusters) pam_result <- pam(ts_df, k = 3) # Extract only rows belonging to Cluster 1 cluster1_df <- ts_df[pam_result$clustering == 1, ]
Scenario 2: You've already added cluster labels to your dataframe
If you merged the cluster labels into a column (e.g., named cluster) in ts_df, the code is even simpler:
# Filter rows where the cluster column equals 1 cluster1_df <- ts_df[ts_df$cluster == 1, ]
Scenario 3: Time series are stored as columns (each column = 1 day)
If your dataframe has time series as columns instead, adjust the indexing to target columns instead of rows:
# Extract only columns belonging to Cluster 1 cluster1_df <- ts_df[, pam_result$clustering == 1]
Verify Your Result
Quickly check that you got the right subset by counting the number of time series in Cluster 1:
# For row-based storage nrow(cluster1_df) # For column-based storage ncol(cluster1_df)
That should give you a clean dataframe with only the time series from Cluster 1!
内容的提问来源于stack exchange,提问作者Maider

