归一化数据框的列(总和等于1) [英] Normalise the columns of a dataframe (sum equal to 1)

查看:266
本文介绍了归一化数据框的列(总和等于1)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下包含权重的数据框df:

Let's say I have the following dataframe df containing weights:

df <- as.data.frame(t(matrix(seq(1,9), nrow = 3, ncol = 3)))
> df

  V1 V2 V3
1  1  2  3
2  4  5  6
3  7  8  9

我想生成一个新的数据帧df_2,其权重归一化(列的总和必须等于1),如下所示:

I would like to produce a new dataframe df_2 with normalised weights (sum of the columns must be equal to 1) as below:

> df_2

   V1         V2          V3
1  0.1666667  0.3333333   0.5
2  0.2666667  0.3333333   0.4
3  0.2916667  0.3333333   0.375

请注意,我对向量w进行归一化的方式如下:

Note that the way I normalise a vector w is the following:

w_normalised <- w/sum(w)


推荐答案

我们需要按数据集的行和除

We need to divide with rowwise sum of the dataset

df/rowSums(df)

这篇关于归一化数据框的列(总和等于1)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆