假设我有:
public function get_books($limit, $offset)
{
/*=== SQL join ===*/
$this->db->select('*');
$this->db->from('category');
$this->db->join('books', 'books.categoryId = category.id');
$this->db->join('users', 'books.userId = users.id'); #...Join three sql table
$this->db->order_by('books.id', 'DESC');
$this->db->where('books.status', '1');
$this->db->limit($limit, $offset);
$query = $this->db->get();
return $query->result();
}
以及以下数据表weights <- c(0.15, 0.25, 0.11, 0.9, 0.35, 0.05)
:
Phones
我想添加一个名为make model price users rating continent market years success
Nokia 3310 800 5000 5 Europe 4000000 30 yes
Huawei Foto 500 10000 7 Asia 1200000 10 no
Apple XS 1500 90000 8 NAmerica 4200000 8 yes
Mi 125 300 500 5 Asia 300000 3 yes
的新列,该列的重量乘以Impact
列
到目前为止,我可以使用以下方法获取列的均值:
price, users, rating, market, and years
因此,我想根据我手动选择的权重进行加权平均。
答案 0 :(得分:2)
加权平均值与矩阵乘法相同,只不过您另外将结果除以权重之和。您有6个砝码和5列,所以我删除了最后一个砝码。
m <- as.matrix(subset(Phones, select = c(price, users, rating, market, years)))
weights <- c(0.15, 0.25, 0.11, 0.9, 0.35)
m %*% weights / sum(weights)
# [,1]
# [1,] 2046239.2
# [2,] 615101.9
# [3,] 2160641.3
# [4,] 153506.6
使用的数据:
Phones <- data.table::fread('
make model price users rating continent market years success
Nokia 3310 800 5000 5 Europe 4000000 30 yes
Huawei Foto 500 10000 7 Asia 1200000 10 no
Apple XS 1500 90000 8 NAmerica 4200000 8 yes
Mi 125 300 500 5 Asia 300000 3 yes
')
答案 1 :(得分:0)