library(haven)
学校联结与心理危机关系 <- read_sav("D:/R/RNETWEIJ/学校联结与心理危机关系.sav")
View(学校联结与心理危机关系)
## 选择数据
data2<-学校联结与心理危机关系[c(1:35)]      
node_labels <- colnames(data2)
groups_list <- list(
  "School Belonging" = grep("^SB", node_labels), # 匹配S开头的
  "Teacher Support" = grep("^TS", node_labels), # 匹配S开头的
  "Peer Support" = grep("^PS", node_labels), # 匹配S开头的
  "Physical Discomfort" = grep("^PD", node_labels),  # 使用正则表达式匹配D开头的
  "Emotional and Behavioral Dysregulation" = grep("^EBD", node_labels),  # 匹配A开头的
  "Cognitive Dysfunction" = grep("^CD", node_labels) # 匹配S开头的
)
groups = groups_list
color = c("#2a5caa", "#76becc","#45b97c","#e7c66b","#e66d50","#ef5b9c")
labels = node_labels
nodenames = list(
   # School Connectedness - BSP (Classmate Support)
  "SB1" = "I can rely on my classmates when I encounter difficulties.",
  "SB2" = "My classmates can genuinely help me.",
  "SB3" = "My classmates can share joys and sorrows with me.",
  "SB4" = "I find it difficult to get along with other classmates.", # Reverse-scored item
  
  # School Connectedness - BST (Teacher Support)
  "TS1" = "I do not like the teachers at my school.", # Reverse-scored item
  "TS2" = "My teachers are very caring and supportive of me.",
  "TS3" = "Teachers at the school treat students fairly.",
  
  # School Connectedness - SIS (School Identification)
  "SB1" = "I feel happy and safe at school.",
  "SB2" = "I am happy to be a member of this school.",
  "SB3" = "I am proud to belong to this school.",
  
  # Psychological Crisis - PD (Physical Discomfort)
  "PD1" = "Experienced gastrointestinal discomfort or diarrhea for an extended period.",
  "PD2" = "Experienced loss of appetite for an extended period.",
  "PD3" = "Experienced headaches for an extended period.",
  "PD4" = "Experienced insomnia or nightmares for an extended period.",
  "PD5" = "Experienced difficulty breathing or a feeling of suffocation for an extended period.",
  "PD6" = "Experienced a sensation of a lump in the throat for an extended period.",
  "PD7" = "Experienced muscle tension for an extended period.",
  
  # Psychological Crisis - EBD (Emotional and Behavioral Dysregulation)
  "EBD1" = "Often engage in self-blame or blame others.",
  "EBD2" = "Often avoid and am reluctant to interact with others.",
  "EBD3" = "Often indulge in the internet or gaming.",
  "EBD4" = "Feel that most people are untrustworthy.",
  "EBD5" = "Feel gloomy and unable to be happy.",
  "EBD6" = "Feel uninterested in everything and experience a sense of oppression.",
  "EBD7" = "Easily become angry over minor issues.",
  "EBD8" = "Feeling lonely and helpless to the point of emotional overwhelm.",
  
  # Psychological Crisis - CD (Cognitive Dysfunction)
  "CD1" = "Have pessimistic or world-weary thoughts.",
  "CD2" = "Feel fear and anxiety about my current situation.",
  "CD3" = "Feel that I am a worthless person.",
  "CD4" = "Feel that people around me are always prejudiced against me.",
  "CD5" = "Tend to dwell on negative thoughts when encountering unfavorable situations.",
  "CD6" = "Do not hold hope for the future.",
  "CD7" = "Feel that I cannot do anything well.",
  "CD8" = "Feel deeply ashamed if I fail to do something well.",
  "CD9" = "Feel that my emotions are out of my control.",
  "CD10" = "Believe that once a person becomes depressed, they cannot escape it."
)
  
## 加载必要包
library(tidyverse)
library(readxl)
library(bootnet)  
library(ggplot2)
library(qgraph) 
library(NetworkComparisonTest)
library(networktools)
## 
network <- estimateNetwork(data2, default = "EBICglasso", threshold = TRUE)
## 1. 提取边权值矩阵
edge_weights <- network$graph
print("边权值矩阵:")
print(round(edge_weights, 3))

## 2. 计算非零边数量
non_zero_edges <- sum(edge_weights != 0) / 2  # 除以2因为矩阵是对称的
total_possible_edges <- ncol(edge_weights) * (ncol(edge_weights) - 1) / 2
edge_density <- non_zero_edges / total_possible_edges

cat("网络统计信息:\n")
cat("节点数量:", ncol(edge_weights), "\n")
cat("非零边数量:", non_zero_edges, "\n")
cat("可能的总边数:", total_possible_edges, "\n")
cat("网络密度:", round(edge_density, 3), "\n")
## 3. 边权值描述性统计
edge_values <- edge_weights[upper.tri(edge_weights)]  # 取上三角避免重复
non_zero_edge_values <- edge_values[edge_values != 0]

cat("\n边权值统计 (非零边):\n")
cat("平均值:", round(mean(non_zero_edge_values), 3), "\n")
cat("标准差:", round(sd(non_zero_edge_values), 3), "\n")
cat("最小值:", round(min(non_zero_edge_values), 3), "\n")
cat("最大值:", round(max(non_zero_edge_values), 3), "\n")
cat("正边数量:", sum(non_zero_edge_values > 0), "\n")
cat("负边数量:", sum(non_zero_edge_values < 0), "\n")
## 4. 创建边权值数据框用于可视化
edges_df <- data.frame(
  from = character(),
  to = character(),
  weight = numeric(),
  stringsAsFactors = FALSE
)

# 提取所有边信息
for(i in 1:(ncol(edge_weights)-1)){
  for(j in (i+1):ncol(edge_weights)){
    if(edge_weights[i,j] != 0){
      edges_df <- rbind(edges_df, data.frame(
        from = node_labels[i],
        to = node_labels[j],
        weight = edge_weights[i,j]
      ))
    }
  }
}

# 按权值绝对值排序
edges_df <- edges_df[order(-abs(edges_df$weight)), ]
print("最强的边连接:")
print(head(edges_df, 20))
## 5. 边权值分布可视化
# 绘制边权值分布直方图
ggplot(edges_df, aes(x = weight)) +
  geom_histogram(bins = 20, fill = "#2a5caa", alpha = 0.7) +
  geom_vline(xintercept = 0, linetype = "dashed", color = "red") +
  labs(title = "边权值分布",
       x = "边权值", 
       y = "频数") +
  theme_minimal()

## 6. 组内和组间连接分析
within_between_edges <- data.frame(
  connection_type = c("SIS组内", "BST组内", "BSP组内", 
                      "SIS-BST", "SIS-BSP", "BST-BSP"),
  count = 0,
  mean_weight = 0,
  stringsAsFactors = FALSE
)

# 计算各组连接
for(i in 1:nrow(edges_df)){
  from_node <- edges_df$from[i]
  to_node <- edges_df$to[i]
  
  # 确定所属组别
  from_group <- ifelse(grepl("^SIS", from_node), "SIS",
                       ifelse(grepl("^BST", from_node), "BST", "BSP"))
  to_group <- ifelse(grepl("^SIS", to_node), "SIS",
                     ifelse(grepl("^BST", to_node), "BST", "BSP"))
  
  # 确定连接类型
  if(from_group == to_group){
    conn_type <- paste0(from_group, "组内")
  } else {
    groups <- sort(c(from_group, to_group))
    conn_type <- paste(groups, collapse = "-")
  }
  
  # 更新统计
  idx <- which(within_between_edges$connection_type == conn_type)
  within_between_edges$count[idx] <- within_between_edges$count[idx] + 1
  within_between_edges$mean_weight[idx] <- within_between_edges$mean_weight[idx] + edges_df$weight[i]
}

# 计算平均权值
within_between_edges$mean_weight <- within_between_edges$mean_weight / within_between_edges$count

print("组内和组间连接统计:")
print(within_between_edges)

## 7. 可视化组间连接
ggplot(within_between_edges, aes(x = connection_type, y = count, fill = connection_type)) +
  geom_bar(stat = "identity") +
  geom_text(aes(label = count), vjust = -0.5) +
  labs(title = "各组连接数量",
       x = "连接类型", 
       y = "边数量") +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

## 绘制网络结构图
plot(network,layout = "spring")
## 美化网路结构图
full_network <- qgraph(
  network$graph,
  posCol = "#181d4b",
  negCol = "#d71345",
  fade = TRUE,
  layout = "spring",
  legend = TRUE,  # 显示图例
  groups = groups_list,  # 使用分组列表
  color = c("#2a5caa", "#76becc","#45b97c","#e7c66b","#e66d50","#ef5b9c"),  # 分组颜色
  vsize = 3.5,
  label.cex = 1,
  legend.cex = 0.35,
  labels = node_labels,  # 使用列名作为标签
  nodeNames = nodenames,
  details = TRUE
)



## 绘制中心性图
centralityPlot(network,
               include = "ExpectedInfluence",  # 仅包含预期影响
               orderBy = "ExpectedInfluence",  # 按预期影响值排序
               scale = "z-score")              # 使用标准化分数（可选）

## 桥中心性
bridge_all <- bridge(network$graph, communities = groups_list)
## 绘制桥中心性图
plot(bridge_all, 
     zscore = TRUE,
     include = c( "Bridge Expected Influence (1-step)"), # 包含的指标
     order = "value")

## 连边指标的非参数bootstrap分析（包括ExpectedInfluence和bridgeExpectedInfluence）
bootnet_nonpar <- bootnet(network, 
                          default = "EBICglasso",
                          statistics = c("strength", "expectedInfluence", 
                                         "bridgeExpectedInfluence"), # 使用正确的统计量名称
                          nBoots = 1000, # bootstrap样本数
                          communities = groups_list, 
                          nCores = 8) 

## 绘制各指标的bootstrap结果
plot(bootnet_nonpar, "expectedInfluence", order = "sample")
plot(bootnet_nonpar, "bridgeExpectedInfluence", order = "sample")

## case-dropping bootstrap分析（计算CS系数）
bootnet_case_dropping <- bootnet(network,
                                 default = "EBICglasso",
                                 statistics = c("strength", "expectedInfluence", 
                                                "bridgeExpectedInfluence"),
                                 nBoots = 1000,
                                 communities = groups_list,
                                 type = "case",
                                 nCores = 8)

# 计算并显示CS系数
corStability(bootnet_case_dropping)

# 绘制中心性稳定性结果（包括ExpectedInfluence和bridgeExpectedInfluence）
plot(bootnet_case_dropping, c("expectedInfluence", "bridgeExpectedInfluence"))










## 中心性分析
centralityPlot(network_all , 
               c("Strength", 
                 "ExpectedInfluence"),  # 包含的中心性指标
               orderBy = "Strength",  # 按照Strength排序
               scale = "z-scores")   # 使用标准化分数

## 中心性分析
centralityPlot(network , 
               c("ExpectedInfluence"), # 包含的中心性指标
               orderBy = "Strength", # 按照Strength排序
               scale = "z-scores")  # 使用标准化分数
## 桥中心性
bridge_all <- bridge(network$graph, communities = groups_list)
## 绘制桥中心性图
plot(bridge_all, 
     zscore = TRUE,
     include = c("Bridge Strength", "Bridge Expected Influence (1-step)"), # 包含的指标
     order = "value")
##  连边指标的非参数bootstrap分析
bootnet_nonpar <- bootnet(network, 
                          default = "EBICglasso",
                          statistics = c("strength", "edge", "closeness", 
                                         "betweenness", "bridgeStrength"), # 分析的指标
                          nBoots = 1000, # bootstrap样本数
                          communities = groups_list, 
                          nCores = 8) 
## 绘制各指标的bootstrap结果
plot(bootnet_nonpar, "strength", order = "sample")
plot(bootnet_nonpar, "edge", order = "sample")
plot(bootnet_nonpar, "bridgeStrength", plot = "difference", order = "sample")
## 计算CS系数
bootnet_case_dropping <- bootnet(network,
                                 default = "EBICglasso",
                                 statistics = c("strength", "edge", "closeness",
                                                "betweenness", "bridgeStrength"),
                                 nBoots = 1000,
                                 communities = groups_list,
                                 type = "case",
                                 nCores = 8)
# 计算并显示CS系数
corStability(bootnet_case_dropping)
# 绘制中心性稳定性结果
plot(bootnet_case_dropping, c("strength", "bridgeStrength"))

library(NetworkComparisonTest)
library(dplyr)
library(tidyr)
# 数据集按性别拆分
data3 <- 学校联结与心理危机关系[c(1:36)]     # 选择数据
# 检查原始数据中的性别列编码
table(data3$gender) # 查看性别分布和编码

# 确保gender列是数值型或可转换为数值型
data3$gender <- as.numeric(as.character(data3$gender))

# 拆分数据
Male <- data3 %>% filter(gender == 1) %>% select(-gender)
Female <- data3 %>% filter(gender == 0) %>% select(-gender)

# 确保所有列都是数值型
Male <- Male %>% mutate(across(everything(), as.numeric))
Female <- Female %>% mutate(across(everything(), as.numeric))

# 删除含有NA的行
Male <- Male %>% drop_na()
Female <- Female %>% drop_na()

# 检查最终的数据结构
str(Male)
str(Female)
# 现在运行NCT
compare_gender <- NCT(Male, Female, 
                      gamma = 0.5,
                      it = 1000,
                      binary.data = FALSE,
                      test.edges = TRUE,
                      edges = "all",
                      communities = groups_list,
                      useCommunities = "all",
                      test.centrality = TRUE,
                      p.adjust.methods = "BH")
summary(compare_gender)
## 提取详细的网络比较结果
# 1全局强度差异结果
compare_gender$glstrinv.pval # p值
compare_gender$glstrinv.real # 实际差异值
plot(compare_gender, what = "strength")  # 绘制强度差异图
# 2网络结构差异结果
compare_gender$nwinv.pval
compare_gender$nwinv.real
plot(compare_gender, what ="network")
# 3边线差异结果
compare_gender$einv.pval
sum(compare_gender$einv.pval$'p-value'<0.05)  # 显著差异边数量
(edgesSign <- compare_gender$einv.pvals[which(compare_gender$einv.pvals[,3]<=.0500),]) # 显著边详情
# 4中心性差异结果
compare_gender$diffcen.pval
## 布局一致的分组网络可视化
# 1保存全样本网络布局
p_all <- plot(network, layout = "spring") 
# 2男性网络估计
network_male <- estimateNetwork(  Male, default = "EBICglasso")
# 3绘制男性网络(使用全样本布局)
plot(network_male, layout = p_all$layout) 
# 4美化男性网络图
full_network <- qgraph( 
  network_male$graph, 
  posCol = "blue", negCol = "red", 
  fade = TRUE,
  layout = full_network$layout, # 保持布局一致 
  legend = TRUE, 
  groups = groups_list,  # 使用分组列表
  color = c("#2a5caa", "#76becc","#45b97c","#e7c66b","#e66d50","#ef5b9c"),  # 分组颜色
  vsize = 5, 
  label.cex = 0.8,
  legend.cex =0.25,
  details = TRUE, 
  title ="心理危机格网络（按维度分组男性）")
# 5女性网络估计
network_female <-estimateNetwork(
  Female,
  default = "EBICglasso")
# 6绘制女性网络
plot(network_female, layout = p_all$layout) 
# 7美化女性网络图
full_network <- qgraph( 
  network_female$graph, 
  posCol = "blue", negCol = "red", 
  fade = TRUE,
  layout = full_network$layout, # 保持布局一致 
  legend = TRUE, 
  groups = groups_list,  # 使用分组列表
  color = c("#2a5caa", "#76becc","#45b97c","#e7c66b","#e66d50","#ef5b9c"),  # 分组颜色
  vsize = 5, 
  label.cex = 0.8,
  legend.cex =0.25,
  details = TRUE, 
  title ="心理危机格网络（按维度分组女性）")