我正在使用cut
函数将数据拆分为使用max / min范围的组。这是我正在使用的代码示例:
# sample data frame - used to identify intial groups
testdf <- data.frame(a = c(1:100), b = rnorm(100))
# split into groups based on ranges
k <- 20 # number of groups
# split into groups, keep code
testdf$groupCode <- cut(testdf$b, breaks = k, labels = FALSE)
# store factor information
testdf$group <- cut(testdf$b, breaks = k)
head(testdf)
我想使用已识别的因子分组来分割另一个数据帧,但我不确定如何使用因子来处理这个问题。我认为我的代码结构大致如下:
# this is the data I want to categorize based on previous groupings
datadf <- data.frame(a = c(1:100), b = rnorm(100))
datadf$groupCode <- function(x){return(groupCode)}
我看到因子数据的结构如下,但我不知道如何正确使用它:
testdf$group[0]
factor(0)
20 Levels: (-2.15,-1.91] (-1.91,-1.67] (-1.67,-1.44] (-1.44,-1.2] ... (2.34,2.58]
我一直在尝试的两个功能(但不起作用)如下:
# get group code
nearestCode <- function( number, groups ){
return( which( abs( groups-number )== min( abs(groups-number) ) ) )
}
nearestCode(7, testdf$group[0])
还尝试了which
功能。
which(7, testdf$group[0])
识别分组并将其应用于其他数据框的最佳方法是什么?
答案 0 :(得分:7)
我会用过:
testdf$groupCode <- cut(testdf$b, breaks =
quantile(testdf$b, seq(0,1, by=0.05), na.rm=TRUE))
grpbrks <- quantile(testdf$b, seq(0,1, by=0.05), na.rm=TRUE)
然后你可以使用:
findInterval(newdat$newvar, grpbrks) # to group new data
然后你就不需要从标签或数据中恢复中断了。
想想,我想你也可以使用:
cut(newdat$newvar, grpbrks) # more isomorphic to original categorization I suppose
答案 1 :(得分:2)
绕过一些正则表达式似乎是实际返回由cut
产生的对象值的唯一方法。
以下代码执行必要的操作:
cut_breaks <- function(x){
first <- as.numeric(gsub(".{1}(.+),.*", "\\1", levels(x))[1])
other <- as.numeric(gsub(".+,(.*).{1}", "\\1", levels(x)))
c(first, other)
}
set.seed(1)
x <- rnorm(100)
cut1 <- cut(x, breaks=20)
cut_breaks(cut1)
[1] -2.2200 -1.9900 -1.7600 -1.5300 -1.2900 -1.0600 -0.8320 -0.6000 -0.3690
[10] -0.1380 0.0935 0.3250 0.5560 0.7870 1.0200 1.2500 1.4800 1.7100
[19] 1.9400 2.1700 2.4100
levels(cut1)
[1] "(-2.22,-1.99]" "(-1.99,-1.76]" "(-1.76,-1.53]" "(-1.53,-1.29]"
[5] "(-1.29,-1.06]" "(-1.06,-0.832]" "(-0.832,-0.6]" "(-0.6,-0.369]"
[9] "(-0.369,-0.138]" "(-0.138,0.0935]" "(0.0935,0.325]" "(0.325,0.556]"
[13] "(0.556,0.787]" "(0.787,1.02]" "(1.02,1.25]" "(1.25,1.48]"
[17] "(1.48,1.71]" "(1.71,1.94]" "(1.94,2.17]" "(2.17,2.41]"
然后,您可以使用cut
参数将这些中断值传递给breaks=
以进行第二次中断。