2017-07-15 47 views
0

我有一个下一个任务如何申请规模规则很多列在新的数据集

a = data.frame(a= c(1,2,3,4,5,6)) # dataset 
range01 <- function(x){(x-min(a$a))/(max(a$a)-min(a$a))} # rule for scale 
b = data.frame(a = 6) # newdaset 
lapply(b$a, range01) # we can apply range01 for this dataset because we use min(a$a) in the rule 

但我怎么可以把这个当我有很多列在我的数据集?像下面

a = data.frame(a= c(1,2,3,4,5,6)) 
b = data.frame(b= c(1,2,3,3,2,1)) 
c = data.frame(c= c(6,2,4,4,5,6)) 
df = cbind(a,b,c) 
df 
new = data.frame(a = 1, b = 2, c = 3) 

我当然可以制定规则,为每个变量

range01a <- function(x){(x-min(df$a))/(max(df$a)-min(df$a))} 

但它很长的路要走。如何使它方便?

回答

1

您可以重新定义您的比例函数,因此它需要两个参数;一个被缩放和一个定标器,如下所示,然后对两个数据帧使用Map

scale_custom <- function(x, scaler) (x - min(scaler))/(max(scaler) - min(scaler)) 

Map(scale_custom, new, df) 
#$a 
#[1] 0 

#$b 
#[1] 0.5 

#$c 
#[1] 0.25 

如果你需要的数据帧结果:

as.data.frame(Map(scale_custom, new, df)) 
# a b c 
#1 0 0.5 0.25 
1

您可以利用以下事实:列名称newdf是相同的。如果两个数据框中列的顺序不相同,可能会有所帮助。

sapply(names(new), function(x) (new[x]-min(df[x]))/(max(df[x])-min(df[x]))) 
#$a.a 
#[1] 0 

#$b.b 
#[1] 0.5 

#$c.c 
#[1] 0.25 

摆在data.frame

data.frame(lapply(names(new), function(x) (new[x]-min(df[x]))/(max(df[x])-min(df[x])))) 
# a b c 
#1 0 0.5 0.25