规范化R data.frame列中的数据 [英] Normalize data in R data.frame column
问题描述
假设我有以下数据:
a <- data.frame(var1=letters,var2=runif(26))
假设我要缩放 var2 $中的每个值c $ c>使得
var2
列的总和等于1(基本上将var2列转换为概率分布)
Suppose I want to scale every value in var2
such that the sum of the var2
column is equal to 1 (basically turn the var2 column into a probability distribution)
我尝试了以下操作:
a$var2 <- lapply(a$var2,function(x) (x-min(a$var2))/(max(a$var2)-min(a$var2)))
这不仅使总和大于1,而且将 var2
列变成一个列表,在该列表上我无法执行 sum
this not only gives an overall sum greater than 1 but also turns the var2
column into a list on which I can't do operations like sum
有没有有效的方法将此列转换为概率分布?
Is there any valid way of turning this column into a probability distribution?
推荐答案
假设您有一个向量 x
,该向量具有非负值且没有 NA
,您可以通过以下方式对其进行标准化:
Suppose you have a vector x
with non-negative values and no NA
, you can normalize it by
x / sum(x)
这是一个适当的概率质量函数。
which is a proper probability mass function.
您进行的转换:
(x - min(x)) / (max(x) - min(x))
仅将 x
重新缩放为 [0,1]
,但不能确保求和到1。
only rescales x
onto [0, 1]
, but does not ensure "summation to 1".
关于您的代码
这里不需要使用 lapply
:
lapply(a$var2, function(x) (x-min(a$var2)) / (max(a$var2) - min(a$var2)))
只需使用矢量化操作
a$var2 <- with(a, (var2 - min(var2)) / (max(var2) - min(var2)))
正如您所说, lapply
给您一个列表,这就是 lapply中的 l所指的。您可以使用 unlist
将该列表折叠为矢量;或者,您可以使用 sapply
,其中 s表示简化(如果可能)。
As you said, lapply
gives you a list, and that is what "l" in "lapply" refers to. You can use unlist
to collapse that list into a vector; or, you can use sapply
, where "s" implies "simplification (when possible)".
这篇关于规范化R data.frame列中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!