合并因子列的值

时间:2013-05-14 10:23:41

标签: r

data$form包含170个唯一的不同值(数字从1到约800)。 我想合并一些值(例如,半径/步长为10)。

我需要这样做才能使用:

colors = rainbow(length(unique(data$form)))

在情节中提供更好的视觉效果。

提前感谢您的帮助。

2 个答案:

答案 0 :(得分:3)

您可以使用%/%对其进行分组,mean将它们和normalize组合起来进行分组。

 # if you want specifically 20 groups:
 groups <- sort(form) %/% (800/20) 

 x <- c(by(sort(form), groups, mean))

 x <- normalize(x, TRUE) * 19 + 1

        0         1         2         3         4 
 1.000000  1.971781  2.957476  4.103704  4.948560 
        5         6         7         8         9 
 5.950617  7.175309  7.996914  8.953086  9.952263 
       10        11        12        13        14 
10.800705 11.901235 12.888889 13.772291 14.888889 
       15        16        17        18        19 
15.927984 16.864198 17.918519 18.860082 20.000000 

答案 1 :(得分:3)

您也可以使用cut。如果使用参数labels=FALSE,则会得到一个整数值:

form <- runif(170, min=1,max=800)
> cut(form, breaks=20)
[1] (518,558]  (280,320]  (240,280]  (121,160]  (757,797]  
[6] (160,200]  (320,359]  (598,638]  (80.8,121] (359,399]  
[7] (121,160]  (200,240] ...
20 Levels: (1.18,41] (41,80.8] (80.8,121] (121,160] (160,200] (200,240] (240,280] (280,320] (320,359] (359,399] (399,439] ... (757,797]

> cut(form, breaks=20, labels=FALSE)
 [1] 14  8  7  4 20  5  9 16  3 10  4  6  5 18 18  6  2 12  
[19] 2  19 13 11 13 11 14 12 17  5 ...

另一方面,我希望您重新考虑用彩虹色绘图,因为它会扭曲读取数据,参见Rainbow Color Map (Still) Considered Harmful