You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在R中运行PROCESS宏(Hayes)有调节中介模型58时遇错误求助

解决R中PROCESS模型58多分类变量报错问题

报错原因分析

你遇到的Error in trunc(mcw) : non-numeric argument to mathematical function,是因为mcx和mcw参数的格式设置错误。PROCESS for R中,这两个参数不需要传入变量的levels列表,而是用逻辑值或数值索引指定多分类变量的处理方式。

修正步骤及代码

1. 修正mcx与mcw参数

  • 对于多分类自变量x(Rec_Cond,5类别),设置mcx = TRUE,让PROCESS自动对其进行虚拟编码(默认以第一个水平为参考类别);如果需要指定其他参考类别,可传入对应水平的索引(比如mcx = 3表示用第3个水平做参考)。
  • 对于多分类调节变量w(PO3_Ex,3类别),同理设置mcw = TRUE或指定参考类别索引。

2. 修正后的完整代码

# Load necessary libraries
if (!require(forcats)) {
  install.packages("forcats", dependencies = TRUE)
  library(forcats)
}

# Set the working directory to where your data and process.R file are located
setwd("MYPATH")

# Check the current working directory to verify the change
cat("Current working directory:", getwd(), "\n")

# Load the data
political_position_data <- read.csv("MYDATA.csv")

# Subset the data to only include entries where CountryCode is 1
us_data <- subset(political_position_data, CountryCode == 1)

# Convert Rec_Cond and PO3_Ex to factors
us_data$Rec_Cond <- as.factor(us_data$Rec_Cond)
us_data$PO3_Ex <- as.factor(us_data$PO3_Ex)

# Convert other covariates to numeric
us_data$BiGender <- as.numeric(as.character(us_data$BiGender))
us_data$BiEducation <- as.numeric(as.character(us_data$BiEducation))
us_data$Bi_Age <- as.numeric(as.character(us_data$Bi_Age))

# Verify the levels of categorical variables
cat("Levels of Rec_Cond:", levels(us_data$Rec_Cond), "\n")
cat("Levels of PO3_Ex:", levels(us_data$PO3_Ex), "\n")

# Print a summary to verify the data preparation
cat("Summary of us_data:\n")
print(summary(us_data))

# Load the PROCESS macro (make sure the file exists in the specified path)
source("process.R")

# Run the PROCESS macro with corrected mcx and mcw parameters
results <- process(data = us_data, 
                   y = "Conf_gov", 
                   x = "Rec_Cond", 
                   m = "STAXI", 
                   w = "PO3_Ex", 
                   cov = c("BiGender", "BiEducation", "Bi_Age"), 
                   model = 58,
                   mcx = TRUE,  # 处理多分类自变量x
                   mcw = TRUE)  # 处理多分类调节变量w

# Print the results
print(results)

3. 额外注意事项

  • 确认Conf_gov(因变量)和STAXI(中介变量)是连续变量,模型58默认适用于连续的y和m;如果这两个变量是分类变量,需要调整模型或使用其他参数。
  • 确保你使用的PROCESS for R版本是最新的,旧版本可能对多分类变量的支持有限。

内容的提问来源于stack exchange,提问作者firstbessy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 05:43:11