本文介绍了在R中使用plyr(ddply)重新缩放的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个csv表,我需要针对该表在每列中0到1之间重新缩放数据.也就是说,任何给定列的最小值将为0,最大值将为1,所有其他值将相应地线性缩放.这是我的脚本:

I've got this csv table for which I need to rescale data between 0 and 1 per each column. That is, the lowest value of any given column will be 0, the highest will be 1, and all other values will be linearly scaled accordingly. Here's my script:

tableau  <- read.csv("/tableau.csv")
tableau.m <- melt(tableau)
tableau.m <- ddply(tableau.m, .(variable), transform,rescale = rescale(value))

(数据如下: https://dl.dropboxusercontent.com/u /73950/tableau.csv )

问题是我需要将第二列("B")反转.也就是说,仅对于此列而不是其他列,最小值应为1,最大值应为0.

The issue is that I need the second column ("B") to be inverted. That is, for this column only and not for the others, the lowest value should be 1, and the highest should be 0.

plyr 是那样灵活的,还是我应该尝试其他方式来实现这一目标?

Is plyr flexible that way, or should I try other ways to achieve this?

(在此示例中,B列应为2.13为白色,1.88为深蓝色,并相应地缩放2.07、2.09、2.05的阴影.另一列应保持不变.)

(In this example, column B should read with 2.13 being white, 1.88 being dark blue, and 2.07's, 2.09's, 2.05's shades being scaled accordingly. The other column should be left untouched.)

推荐答案

基于variable的值,使用ifelse选择缩放方向怎么办:

What about using ifelse to select the scaling direction, based on the value of variable:

tableau.m = ddply(tableau.m, .(variable), transform,
                  rescale = ifelse(variable=="B",
                                   rescale(value, to=c(1,0)), rescale(value)))

   Net variable value    rescale
1    a        B  1.88 1.00000000
2    b        B  2.05 0.32000000
3    c        B  2.09 0.16000000
4    d        B  2.07 0.24000000
5    e        B  2.13 0.00000000
6    a        C  0.15 0.00000000
7    b        C  0.23 0.21621622
8    c        C  0.29 0.37837838
9    d        C  0.52 1.00000000
10   e        C  0.30 0.40540541
11   a        D  0.60 1.00000000
12   b        D  0.51 0.72727273
13   c        D  0.40 0.39393939
14   d        D  0.36 0.27272727
15   e        D  0.27 0.00000000
16   a    E..e. 10.00 0.04109589
17   b    E..e. 55.00 0.65753425
18   c    E..e. 58.00 0.69863014
19   d    E..e. 80.00 1.00000000
20   e    E..e.  7.00 0.00000000
21   a    F..f. 90.00 1.00000000
22   b    F..f. 80.00 0.00000000
23   c    F..f. 88.00 0.80000000
24   d    F..f. 84.00 0.40000000
25   e    F..f. 90.00 1.00000000

这篇关于在R中使用plyr(ddply)重新缩放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 04:01