【发布时间】:2018-11-01 19:19:29
【问题描述】:
我在下面有一个数据集,其中包含按周分组的销售数据和其他数据:
df
Market Week Sales diff_data1 another2
1 1 1 5 30 -40
2 1 2 4 7 -8
3 1 3 7 100 9
4 1 4 11 92 50
5 2 1 8 0 8
6 2 2 5 0 14
7 2 3 8 9 98
8 2 4 1 3 3
我的目标是以两种不同的方式对数据进行归一化:均值归一化和最小归一化。对销售数据进行平均归一化,而对非销售数据进行最小归一化。我认为我的平均归一化是正确的,但最小归一化有点棘手,因为我对选择的数据有条件。以下是我目前拥有的。
##Function to standardizing variables
group = "Market"
date = "Week"
##Function to standardize sales by dividing by the standard deviation of sales
normalized_mean <- function(x){
return(x/(sd(x)))
}
##Function to standardize variables by subtracting min
##Used for non-sales data
normalized_min<-function(x){
out<- ifelse(x>0, ((x-min(x)) / sd(x)),
ifelse(x<0, ((x+max(x)) / sd(x)),
ifelse(x==0, 0,0)))
return(out)
}
if (!("Sales" %in% colnames(df))){
df_index<-df %>%
dplyr::group_by(!!sym(group)) %>%
dplyr::mutate_at(vars(-one_of(!!group,!!date)), normalized_min)
} else {
df_index<-df %>%
dplyr::group_by(!!sym(group)) %>%
dplyr::mutate_at(vars(-one_of(!!group,!!date)), normalized_mean)
}
这个的当前输出是:
df_index
Market Week Sales diff_data1 another2
1 1 1 1.62 0.655 -1.07
2 1 2 1.29 0.153 -0.213
3 1 3 2.26 2.18 0.240
4 1 4 3.55 2.01 1.33
5 2 1 2.41 0 0.178
6 2 2 1.51 0 0.311
7 2 3 2.41 2.12 2.17
8 2 4 0.302 0.707 0.0666
输出应该是这样的:
Market Week Sales diff_data1 another2
1 1 1 1.62 0.501 0.26679
2 1 2 1.29 0 1.12053
3 1 3 2.26 2.02 1.30729
4 1 4 3.55 1.85 2.40114
5 2 1 2.41 0 7.93342
6 2 2 1.51 0 13.9334
7 2 3 2.41 2.121 97.9334
8 2 4 0.302 0.707 2.93342
我的问题是下面的这个公式。
如何使条件适用于此类示例?好像没有考虑x>0、x<0、x==0的条件。
normalized_min<-function(x){
out<- ifelse(x>0, ((x-min(x)) / sd(x)),
ifelse(x<0, ((x+max(x)) / sd(x)),
ifelse(x==0, 0,0)))
return(out)
}
任何帮助都会很棒,谢谢!
【问题讨论】:
标签: r indexing normalization