r - R 0 到 5 的标准化

标签 r dplyr normalization normalize

我有一个数据框如下:

  A       B         C
 ab      gb      0.03
 fn      mn      0.12
 po      er      0.43
 oo      et      0.22
 iu      ew      0.77
 ii      mn      0.14
 dd      wr      0.99
 qw      ty      0.45

如何将 C 列标准化为 0-5 范围内的值。我知道你可以用 dplyr 这样做,但它不会将其转换为 0-5。

normalize <- function(x){
  return((x-min(x)) / (max(x)-min(x)))
}

scaled_data <- 
  df %>%
  group_by(A, B) %>%
  mutate(NORMALIZED = normalize(C))

最佳答案

以下是如何通过 dplyr 使用 scales::rescale 来完成此操作。我将让您添加 group_by

df <-read.table(text="  A       B         C
 ab      gb      0.03
 fn      mn      0.12
 po      er      0.43
 oo      et      0.22
 iu      ew      0.77
 ii      mn      0.14
 dd      wr      0.99
 qw      ty      0.45",header=TRUE,stringsAsFactors=FALSE)

df%>%
mutate(C=scales::rescale(C,to=c(0, 5)))

   A  B        C
1 ab gb 0.000000
2 fn mn 0.468750
3 po er 2.083333
4 oo et 0.989583
5 iu ew 3.854167
6 ii mn 0.572917
7 dd wr 5.000000
8 qw ty 2.187500

关于r - R 0 到 5 的标准化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43594712/

相关文章:

r - 为什么不建议在 R 中使用 attach(),我应该使用什么?

r - 如果上面缺少值,则将列中的值向上移动

R - 如何按列索引使用 dplyr left_join?

database - SQLite3 数据库中的派生字段

mysql - sql - 使用它的组规范用户表,但两者都可以登录

ruby-on-rails - Rails 模型标准化

r - 使用 rma.glmm : Error when the 2 estimates are identical 计算估计值

mysql - 如何在 RMySQL 中简洁地引用数据框

r - R 中带有子集的 For 循环

r - ggplot2 图的子集数据