按组标准化 [英] Normalize by Group

查看:37
本文介绍了按组标准化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试按项目标准化强度代码

I'm trying to normalize the StrengthCode by Item

例如

ID    Item    StrengthCode
7     A       1
7     A       5
7     A       7
8     B       1
8     B       3
9     A       5
9     A       3

我需要实现的是这样的:

What I need to achieve is something like this:

ID    Item    StrengthCode    Nor
7     A       1    0.14
7     A       5    0.71
7     A       7    1
8     B       1    0.34
8     B       3    1
9     A       5    0.71
9     A       3    0.42

我试过这段代码,但我被卡住了......如果你能帮助我会很棒!!!

I tried this code but I'm stuck.... if you can help me would be awesome!!!

normalit <- function(m){(m - min(m))/(max(m)-min(m))}

Tbl.Test <- Tbl.3.1 %>%
  group_by(ID, Item) %>%
  mutate(Nor = normalit(StregthCode))

我收到此错误:

由强制引入的警告消息 NAs

Warning message NAs introduced by coercion

推荐答案

你想要的输出看起来像你想要的:

Your desired output looks like you are wanting this:

df <- read.table(header=TRUE, text=
'ID    Item    StrengthCode
7     A       1
7     A       5
7     A       7
8     B       1
8     B       3
9     A       5
9     A       3')
df$Nor <- ave(df$StrengthCode, df$Item, FUN=function(x) x/max(x)) 
df
# > df
#   ID Item StrengthCode       Nor
# 1  7    A            1 0.1428571
# 2  7    A            5 0.7142857
# 3  7    A            7 1.0000000
# 4  8    B            1 0.3333333
# 5  8    B            3 1.0000000
# 6  9    A            5 0.7142857
# 7  9    A            3 0.4285714

使用 dplyr 你可以做到(感谢 Sotos 的评论+代码):

With dplyr you can do (thx to Sotos for the comment+code):

library("dplyr")
(df %>% group_by(Item) %>% mutate(Nor = StrengthCode/max(StrengthCode))) 
# > (df %>% group_by(Item) %>% mutate(Nor = StrengthCode/max(StrengthCode)))
# Source: local data frame [7 x 4]
# Groups: Item [2]
# 
#      ID   Item StrengthCode       Nor
#   <int> <fctr>        <int>     <dbl>
# 1     7      A            1 0.1428571
# 2     7      A            5 0.7142857
# 3     7      A            7 1.0000000
# 4     8      B            1 0.3333333
# 5     8      B            3 1.0000000
# 6     9      A            5 0.7142857
# 7     9      A            3 0.4285714

这篇关于按组标准化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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