R语言按指定加权公式为数据框新增Weight计算列
R实现按规则为data.frame新增Weight列
计算规则
核心公式:Weight = Mode + (constant * mean)
参数说明:
Mode:现有database数据集中已存在的列constant:本次共10个Alternative,固定取值为0.1(即1/10)mean:单条Alternative对应的所有Method列数值的算术平均值,例如alternative 10的均值为(3 + 2 + 2 + 3)/4 = 2.5
校验示例:alternative 10代入公式计算得Weight = 2 + (0.1 * 2.5) = 2.25
完整可运行代码
代码基于R基础函数实现,无需安装额外依赖包:
# 加载示例数据集 database <- structure(list(Alternatives = c(3, 4, 5, 6, 7, 8, 9, 10, 11, 12), Method1 = c(1L, 10L, 7L, 8L, 9L, 6L, 5L, 3L, 4L, 2L), Method2 = c(1L, 8L, 6L, 7L, 10L, 9L, 4L, 2L, 3L, 5L), Method3 = c(1L, 10L, 7L, 8L, 9L, 6L, 4L, 2L, 3L, 5L), Method4 = c(1L, 9L, 6L, 7L, 10L, 8L, 5L, 3L, 4L, 2L), Mode = c(1, 10, 6, 7, 9, 6, 4, 2, 3, 2)), class = "data.frame", row.names = c(NA,-10L)) # 定义常量,自动匹配Alternative总数,本例计算结果为0.1 constant <- 1 / nrow(database) # 计算所有Method列的行均值,生成Weight列 database$Weight <- database$Mode + constant * rowMeans(database[, startsWith(names(database), "Method")])
运行结果
代码运行后alternative 10对应的Weight值为2.25,与示例计算结果完全匹配,完整数据集输出如下:
Alternatives Method1 Method2 Method3 Method4 Mode Weight 1 3 1 1 1 1 1 1.100 2 4 10 8 10 9 10 10.925 3 5 7 6 7 6 6 6.650 4 6 8 7 8 7 7 7.750 5 7 9 10 9 10 9 9.950 6 8 6 9 6 8 6 6.725 7 9 5 4 4 5 4 4.450 8 10 3 2 2 3 2 2.250 9 11 4 3 3 4 3 3.350 10 12 2 5 5 2 2 2.350
内容的提问来源于stack exchange,提问作者Antonio
相关产品推荐
相关产品推荐

