2014-07-17 10 views
3

我想創建連續變量之外的分箱變量。我想要10個垃圾箱,並根據詹克斯分類的結果設置中斷點。我如何將每個值分配給這10個分檔中的一個?根據班級間隔確定的結果創建分箱變量

# dataframe w/ values (AllwdAmt) 
df <- structure(list(X = c(2078L, 2079L, 2080L, 2084L, 2085L, 2086L, 
2087L, 2092L, 2093L, 2094L, 2095L, 4084L, 4085L, 4086L, 4087L, 
4088L, 4089L, 4091L, 4092L, 4093L, 4094L, 4095L, 4096L, 4097L, 
4098L, 4099L, 4727L, 4728L, 4733L, 4734L, 4739L, 4740L, 4741L, 
4742L, 4743L, 4744L, 4745L, 4746L, 4747L, 4748L, 4749L, 4750L, 
4751L, 4752L, 4753L, 4754L, 4755L, 4756L, 4757L, 4758L), AllwdAmt = c(34.66, 
105.56, 105.56, 473.93, 108, 1669.23, 201.5, 62.67, 61.54, 601.28, 
236.96, 108, 40.28, 29.32, 483.6, 236.96, 6072.4, 25.97, 120.9, 
61.54, 32.18, 473.93, 302.25, 0, 8.48, 3140.18, 0, 0, 6.83, 6.83, 
895.44, 895.44, 24.11, 24.11, 32.18, 32.18, 236.96, 236.96, 11.96, 
11.96, 80.08, 80.08, 3140.18, 3140.18, 163.62, 163.62, 236.96, 
236.96, 216.01, 216.01)), .Names = c("X", "AllwdAmt"), row.names = c(1137L, 
1138L, 1139L, 1140L, 1141L, 1142L, 1143L, 1144L, 1145L, 1146L, 
1147L, 1945L, 1946L, 1947L, 1948L, 1949L, 1950L, 1951L, 1952L, 
1953L, 1954L, 1955L, 1956L, 1957L, 1958L, 1959L, 2265L, 2266L, 
2267L, 2268L, 2269L, 2270L, 2271L, 2272L, 2273L, 2274L, 2275L, 
2276L, 2277L, 2278L, 2279L, 2280L, 2281L, 2282L, 2283L, 2284L, 
2285L, 2286L, 2287L, 2288L), class = "data.frame") 

# get class intervals. This shows where the breaks should be. 
library(classInt) 
classIntervals(df$AllwdAmt, n = 10, style = 'jenks') 

# Output: 
style: jenks 
    [0,140.48] (140.48,396.26] (396.26,799.55] (799.55,1338.18] (1338.18,1864.02]   
     1109    423    111    97    58     
    (1864.02,2586] (2586,3451.35] (3451.35,5049.74] 
    12    44    20 
    (5049.74,6342.5] (6342.5,10407.88] 
      33     2 

# A very inefficient way to assign breaks, based on output from above classIntervals: 
df$AllwdBin <- ifelse(df$AllwdAmt <= 140.48,1, 
          ifelse(df$AllwdAmt > 140.48 & df$AllwdAmt <= 396.26,2, 
           ifelse(df$AllwdAmt > 396.26 & df$AllwdAmt <= 799.55,3… 

# The start of my code & associated error for automatically assigning a bin with breaks  
# coming from Jenks classification: 

df$AllwdBin <- cut(df$AllwdAmt, breaks = classIntervals(df$AllwdAmt, n = 10, style =  
'jenks'), labels = c(as.character(1:10))) 

# Output 
Error in is.factor(x) : (list) object cannot be coerced to type 'double' 

我明白了上面的錯誤涉及到這樣一個事實:classintervals輸出生產值的列表,但是如何把這個列表轉化爲有意義的突破?

回答

7

看的classIntervals()輸出這樣的names

foo <- classIntervals(df$AllwdAmt, n=10, style='jenks') 
names(foo) 

這會告訴你,foo有兩個條目,varbrks

您需要使用此輸出的$brks組件:

cut(df$AllwdAmt, breaks = foo$brks, labels=as.character(1:10)) 
+0

我有時候回頭看看我的老問題,並意識到我是多麼笨是以前了。甚至dumberer。 – NiuBiBang

+2

我在SO之前的時間裏做了我的啞巴問題,所以他們沒有保留所有的時間。對某種語言來說,或多或少是一種新的東西,並不是愚蠢的。 –

相關問題