将邻接表转换为seminr测量模型的程序化实现方法
用R语言将邻接表转换为seminr包的测量模型格式
问题背景
你手头有一份名为df的邻接表数据,需要将其程序化转换为适配R语言seminr包的测量模型格式,目标格式明确,但不清楚如何用do.call实现这一转换。
示例数据
df <- read.table(text = " from to column_position 1 a V7 11 2 b V7 15 3 c V7 10 4 a V7 9 5 b V7 12 6 c V16 17 7 a V16 5 8 b V16 27 9 c V16 6 10 a V16 20 11 b V16 14 12 c V16 7 13 a V14 19 14 b V14 18 15 c V20 24 16 a C5 21 17 b C5 28 18 c C13 22 19 a C13 23 20 b C16 26 21 c C16 16 22 a C16 25 23 b C15 8 24 c C15 13", header = TRUE)
seminr测量模型常规写法参考
library(seminr) mobi_mm <- constructs( reflective("Image", multi_items("IMAG", 1:5)), reflective("Expectation", multi_items("CUEX", 1:3)), reflective("Quality", multi_items("PERQ", 1:7)), reflective("Value", multi_items("PERV", 1:2)), reflective("Satisfaction", multi_items("CUSA", 1:3)), reflective("Complaints", single_item("CUSCO")), reflective("Loyalty", multi_items("CUSL", 1:3)) )
期望输出格式示例
mobi_mm <- constructs( reflective("V7", multi_items(item_numbers = c(9,10,11,12,15))), reflective("V16", multi_items(item_numbers = c(5,6,7,14,17,20,27))), reflective("V14", multi_items(item_numbers = c(18,19))), reflective("V20", single_item(item_number = 24)), reflective("C5", multi_items(item_numbers = c(21,28))), reflective("C13", multi_items(item_numbers = c(22,23))), reflective("C16", multi_items(item_numbers = c(16,25,26))), reflective("C15", multi_items(item_numbers = c(8,13))) )
解决方案
核心逻辑是:按构念(to列)分组整理题项位置,生成每个构念对应的reflective调用,最后用do.call将所有调用批量传入constructs函数。
方法1:Base R实现
library(seminr) # 按构念拆分数据,提取并排序题项位置 split_data <- split(df$column_position, df$to) split_data <- lapply(split_data, sort) # 生成每个构念的reflective调用 construct_calls <- lapply(names(split_data), function(construct) { items <- split_data[[construct]] # 根据题项数量选择multi_items或single_item item_call <- if(length(items) > 1) { call("multi_items", item_numbers = items) } else { call("single_item", item_number = items) } call("reflective", construct, item_call) }) # 批量构建测量模型 mobi_mm <- do.call(constructs, construct_calls)
方法2:dplyr+tibble实现(更直观的分组操作)
library(seminr) library(dplyr) # 分组整理构念与对应题项 construct_data <- df %>% group_by(to) %>% summarise(items = sort(column_position), .groups = "drop") # 生成调用列表 construct_calls <- pmap(construct_data, function(to, items) { item_call <- if(length(items) > 1) { call("multi_items", item_numbers = items) } else { call("single_item", item_number = items) } call("reflective", to, item_call) }) # 构建测量模型 mobi_mm <- do.call(constructs, construct_calls)
代码解释
- 分组整理:将邻接表按
to列(构念名)拆分,收集每个构念对应的所有题项位置并排序,让生成的代码更整洁。 - 生成调用:对每个构念,根据题项数量选择
multi_items或single_item,用call()函数生成对应的函数调用表达式。 - 批量构建:通过
do.call将所有reflective调用作为参数传递给constructs,实现程序化生成测量模型。
内容的提问来源于stack exchange,提问作者MaskofIllusion
相关产品推荐
相关产品推荐

