3

快速提问。我以多种不同的方式对变量进行分类以进行探索性数据分析。假设我有一个名为vardata.frame的变量df

df$var<-c(1,2,8,9,4,5,6,3,6,9,3,4,5,6,7,8,9,2,3,4,6,1,2,3,7,8,9,0)

到目前为止,我采用了以下方法(下面的代码):

#Divide into quartiles
df$var_quartile <- with(df, cut(var, breaks=quantile(var, probs=seq(0,1, by=.25)), include.lowest=TRUE))
# Values of var_quartile
> [0,3],[0,3],(7.25,9],(7.25,9],(3,5],(3,5],(5,7.25],[0,3],(5,7.25],(7.25,9],[0,3],(3,5],(3,5],(5,7.25],(5,7.25],(7.25,9],(7.25,9],[0,3],[0,3],(3,5],(5,7.25],[0,3],[0,3],[0,3]

#Bin into increments of 2
df$var_bin<- cut(df[['var']],2, include.lowest=TRUE, labels=1:2)
# Values of var_bin
> 1 1 2 2 1 2 2 1 2 2 1 1 2 2 2 2 2 1 1 1 2 1 1 1 2 2 2 1

我想做的最后一件事是将变量按时间顺序排序后分成 10 个观察的部分。这是在找到中位数后进行拆分的相同方法(计数到中间观察值),只是我想以 10 个观察值为增量进行计数。

使用我的示例,这将分为var以下部分:

0,1,1,2,2,2,3,3,3,3
4,4,4,5,5,6,6,6,6,7
7,8,8,8,9,9,9

注意——我需要在非常大的数据集中运行这个操作(通常是 3-600 万个宽幅观察)。

我该怎么做呢?谢谢!

4

5 回答 5

8

cut_number()from ggplot2旨在将数字向量切割成包含相等数量点的间隔。在您的情况下,您可以像这样使用它:

library(ggplot2)
split(var, cut_number(var, n=3, labels=1:3))
# $`1`
#  [1] 1 2 3 3 2 3 1 2 3 0
# 
# $`2`
# [1] 4 5 6 6 4 5 6 4 6
# 
# $`3`
# [1] 8 9 9 7 8 9 7 8 9
于 2013-03-07T16:58:02.150 回答
4
vec <- c(1,2,8,9,4,5,6,3,6,9,3,4,5,6,7,8,9,2,3,4,6,1,2,3,7,8,9,0) # your vector

nObs <- 10 # number of observations per bin

# create data labels
datLabels <- ceiling(seq_along(vec)/nObs)[rank(vec, ties.method = "first")] 


# test data labels:
split(vec, datLabels)

$`1`
 [1] 1 2 3 3 2 3 1 2 3 0

$`2`
 [1] 4 5 6 6 4 5 6 7 4 6

$`3`
 [1] 8 9 9 8 9 7 8 9
于 2013-03-07T15:36:54.083 回答
1

你的意思是这样的吗?

x <- sample(100)
binSize <- 10
table(floor(x/binSize)*binSize)
于 2013-03-07T15:20:17.920 回答
1

我在不使用剪切的情况下创建了相同大小的组。

# number_of_groups_wanted  = number of rows / divisor in ceiling code  
# therefore divisor in ceiling code should be =  number of rows / number_of_groups_wanted, 
# divisor in ceiling code = (nrow(df)/number_of_groups_wanted)  
# min assigns every tied element to the lowest rank 
number_of_groups_wanted = 100 # put in the number of groups you want
df$group = ceiling(rank(df$var_to_group, ties.method = "min")/(nrow(df)/number_of_groups_wanted)) 

df$rank = rank(df$var_to_group, ties.method = "min") # this line is just used to check data  
于 2017-09-04T22:59:26.637 回答
0

这应该这样做。

df$var_bin<- cut(df[['var']], breaks = Size(df$var/10), 
                 include.lowest=TRUE, labels=1:10)
于 2013-03-07T15:36:55.030 回答