R 如何为新数据集中的多个列应用缩放规则
我有下一个任务R 如何为新数据集中的多个列应用缩放规则,r,scale,R,Scale,我有下一个任务 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
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
当然,我可以为每个变量制定规则
range01a <- function(x){(x-min(df$a))/(max(df$a)-min(df$a))}
range01a您可以重新定义缩放函数,使其包含两个参数;一个要缩放,一个按如下所示使用缩放器,然后在两个数据帧上使用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
可以重新定义缩放函数,使其包含两个参数;一个要缩放,一个按如下所示使用缩放器,然后在两个数据帧上使用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
您可以利用new
和df
的列名相同这一事实。如果两个数据帧中的列顺序不同,则可能会有所帮助
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
您可以利用new
和df
的列名相同这一事实。如果两个数据帧中的列顺序不同,则可能会有所帮助
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