如何使用函数 R sweep

huangapple go评论48阅读模式
英文:

How to use the function R sweep

问题

如何使用R中的sweep函数

在R中,我想要使用Sweep函数。

我不想使用meansd进行缩放,而是想使用minmax

我想要在矩阵中计算这个式子:yi = (xi - min(x)) / (max(x) - min(x))

我不知道该如何操作,感谢您的回答。

英文:

How to use the function R sweep

In R, I whant to use the function sweep.

I dont whant to scale using mean and sd, but min and max.

I whant to calculate this yi = (xi - min(x)) / (max(x) - min(x)) in a matrix.

I don't know how to do, thank you for your answer ?

答案1

得分: 3

1:

dat <- data.matrix(iris)
apply(dat, 2, \(x)(x - min(x))/(max(x) - min(x)))

2:

r <- matrixStats::colRanges(dat)
scale(dat, r[,1], diff(t(r)))

3:

sapply(data.frame(dat), scales::rescale)

我已为您翻译了代码部分。

英文:

Ways to go about this:

1:

dat <- data.matrix(iris)
apply(dat, 2, \(x)(x - min(x))/(max(x) - min(x)))

2:

r <- matrixStats::colRanges(dat)
scale(dat, r[,1], diff(t(r))

3:

sapply(data.frame(dat), scales::rescale)

I highly doubt sweep can be used for this particular problem

答案2

得分: 2

你可能正在寻找 apply,例如,这是如何在矩阵的每一列上使用缩放的示例:

m <- matrix(runif(25), nc = 5)

my_scale <- function(v) (v - min(v)) / (max(v) - min(v))
m_scaled <- apply(m, 2, FUN = my_scale)
英文:

You may be looking for apply, e.g. here is how to use your scaling on each column of a matrix:

m &lt;- matrix(runif(25), nc = 5)

my_scale &lt;- function(v) (v - min(v)) / (max(v) - min(v))
m_scaled &lt;- apply(m, 2, FUN = my_scale)

huangapple
  • 本文由 发表于 2023年5月30日 01:20:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/76359235.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定