R语言函数中如何将参数值赋值给矩阵dimnames的名称
解决R语言函数中用参数值为矩阵dimnames命名的问题
你遇到的核心问题是:在定义矩阵dimnames时,直接使用test1 = ...这种写法会把参数名当成维度名,而非参数传入的实际字符串值。加上函数内部又重新给test1和test2赋值为数据子集,导致原始参数值被覆盖,更没法直接调用。
修改方案
- 先保存原始参数值:在函数开头把传入的
test1和test2字符串存为新变量,避免后续赋值覆盖; - 动态设置维度名:用
setNames或手动给列表命名的方式,把保存的原始参数值作为维度的名称。
修改后的完整函数
mcm_fun <- function(technique, test1, test2){ # 保存原始参数值,用于后续维度命名 row_dim_name <- test1 col_dim_name <- test2 # 原有数据处理逻辑不变 test1 <- mcmr[mcmr$type == test1 & mcmr$teq == technique, "value"] test2 <- mcmr[mcmr$type == test2 & mcmr$teq == technique, "value"] # 动态构建dimnames:用原始参数值作为维度的名称 matrix(c(table(test1), table(test2)), nrow = 2, dimnames = list( setNames(list(c("Positive", "Negative")), row_dim_name), setNames(list(c("Positive", "Negative")), col_dim_name) )) }
测试调用
mcm_fun("string", "mg", "xp")
输出结果
mg xp Positive Negative Positive 1 3 Negative 3 1
另一种等价写法
如果觉得setNames麻烦,也可以先创建无命名的dimnames列表,再给列表命名:
mcm_fun <- function(technique, test1, test2){ row_dim_name <- test1 col_dim_name <- test2 test1 <- mcmr[mcmr$type == test1 & mcmr$teq == technique, "value"] test2 <- mcmr[mcmr$type == test2 & mcmr$teq == technique, "value"] dim_names <- list( c("Positive", "Negative"), c("Positive", "Negative") ) # 给dimnames列表设置名称 names(dim_names) <- c(row_dim_name, col_dim_name) matrix(c(table(test1), table(test2)), nrow = 2, dimnames = dim_names) }
内容的提问来源于stack exchange,提问作者jpsmith
相关产品推荐
相关产品推荐

