R语言中实现数组列表与数据框列表对应元素相乘
R语言:数组列表与数据框列表对应元素逐行相乘
我需要实现:将数组列表mat1中的每个数组(emote、sceng),与数据框列表df1中对应的数据框(同名称的emote、sceng)做逐行相乘——即数组的A、B列数值,分别和对应数据框的value列数值按行相乘。但之前的尝试都未得到预期结果。
数据定义
mat1 <- list(emote = structure(c(32.159, -3.608, -4.763, 5.394, 8.581, 71.258, 0.427, -0.323, 10.427, 21.967), dim = c(5L, 2L), dimnames = list(c("(Icpt)", "pl", "ed", "fin", "hp"), c("A", "B"))), sceng = structure(c(105.992, -0.011, 5.847, -10.575, -24.148, 229.327, 7.864, 18.654, -3.56, -8.6), dim = c(5L, 2L), dimnames = list(c("(Icpt)", "pl", "ed", "fin", "hp"), c("A", "B")))) df1 <- list(emote = structure(list(Var1 = structure(1:5, levels = c("(Icpt)", "pl", "ed", "fin", "hp"), class = "factor"), value = c(0.079, 0.013, 0.005, 0.017, 0.013)), row.names = c(NA, -5L), class = "data.frame"), sceng = structure(list(Var1 = structure(1:5, levels = c("(Icpt)", "pl", "ed", "fin", "hp"), class = "factor"), value = c(0.136, 0.027, 0.009, 0.032, 0.021)), row.names = c(NA, -5L), class = "data.frame"))
尝试过的无效代码
lapply(mat1, '*', df1):无法正确配对列表元素,且未处理数据框中的非数值列mapply(function(x, y) if(all(is.numeric(x), is.numeric(y))) x * y else x, mat1, df1):未提取数据框中的value列,直接操作数据框导致维度不匹配
正确解法
核心是提取数据框的value列向量,再与对应数组做逐行广播相乘(R会自动将向量匹配数组的行维度),用mapply实现列表元素的一一配对处理:
# 对应元素相乘,保留列表结构 result <- mapply(function(mat, df) { mat * df$value }, mat1, df1, SIMPLIFY = FALSE) # 格式化结果为4位小数,与预期一致 lapply(result, round, 4)
运行结果
$emote A B (Icpt) 2.5406 5.6294 pl -0.0469 0.0056 ed -0.0238 -0.0016 fin 0.0917 0.1773 hp 0.1116 0.2856 $sceng A B (Icpt) 14.4149 31.1885 pl -0.0003 0.2123 ed 0.0526 0.1679 fin -0.3384 -0.1139 hp -0.5071 -0.1806
内容的提问来源于stack exchange,提问作者GSA
相关产品推荐
相关产品推荐

