【发布时间】:2018-05-21 02:53:11
【问题描述】:
我正在尝试创建与我的数据框值相对应的十分位数因子。我希望这些因素显示为一个范围,例如如果值为“164”,则分解结果应为“160 - 166”。
过去我会这样做:
quantile(countries.Imported$Imported, seq(0,1, 0.1), na.rm = T) # display deciles
Imported.levels <- c(0, 1000, 10000, 20000, 30000, 50000, 80000) # create levels from observed deciles
Imported.labels <- c('< 1,000t', '1,000t - 10,000t', '10,000t - 20,000t', etc) # create corresponding labels
colfunc <- colorRampPalette(c('#E5E4E2', '#8290af','#512888'))
# apply factor function
Imported.colors <- colfunc(10)
names(Imported.colors) <- Imported.labels
countries.Imported$Imported.fc <- factor(
cut(countries.Imported$Imported, Imported.levels),labels = Imported.labels)
相反,我想应用一个函数,将值分解为十分位数范围。我想避免手动设置因子标签,因为我将运行许多查询并绘制具有离散图例的地图。我创建了一个名为 Value.fc 的列,但我无法将其从 "(160, 166]" 格式化为 "160 - 166"。请参阅下面有问题的代码:
corn_df <- corn_df %>%
mutate(Value.fc = gtools::quantcut(Value, 10))
corn_df %>%
select(Value, unit_desc, domain_desc, Value.fc) %>%
head(6)
A tibble: 6 x 4 Value unit_desc domain_desc Value.fc <dbl> <chr> <chr> <fct> 1 164. BU / ACRE TOTAL (160,166] 2 196. BU / ACRE TOTAL (191,200] 3 203. BU / ACRE TOTAL (200,230] 4 205. BU / ACRE TOTAL (200,230] 5 172. BU / ACRE TOTAL (171,178] 6 213. BU / ACRE TOTAL (200,230]
【问题讨论】:
-
如果
Value.fc <- cut(vec, breaks=quantile(vec, seq(0,1,len=11))-c(1,rep(0,10)))可以创建等分因子,那么gsub("\\(([-.0-9]+),([-.0-9]+)\\]$", "\\1-\\2", levels(Value.fc))将从(lo,hi]变为lo-hi。 -
谢谢@r2evans
标签: r cut quantile discretization