从R中的'cut()'输出一个数值

And*_*rew 6 cut r

我在这里读到了这个问题: 按间隔分组数值

但是,我想输出一个数字(而不是一个因子),特别是下限和/或上限的数值(在单独的列中)

从本质上讲,这是正确的,除了'df $ start'和'df $ end'是作为因素给出的:

df$start <- cut(df$x, 
                breaks = c(0,25,75,125,175,225,299),
                labels = c(0,25,75,125,175,225),
                right = TRUE)

df$end <- cut(df$x, 
              breaks = c(0,25,75,125,175,225,299),
              labels = c(25,75,125,175,225,299),
              right = TRUE)
Run Code Online (Sandbox Code Playgroud)

'as.numeric()'的使用返回因子的级别(即值1-6)而不是原始数字.

谢谢!

use*_*691 8

大部分行为cut都与创建您不感兴趣的标签有关.您可能最好使用findInterval.bincode.

您将从数据开始

set.seed(17)
df <- data.frame(x=300 * runif(100))
Run Code Online (Sandbox Code Playgroud)

然后设置休息并找到间隔:

breaks <- c(0,25,75,125,175,225,299)
df$interval <- findInterval(df$x, breaks)
df$start <- breaks[df$interval]
df$end <- breaks[df$interval + 1]
Run Code Online (Sandbox Code Playgroud)


csg*_*pie 6

我在猜测您想要的是什么,因为如果您想要“原始数字”,则可以使用df$x。我想你是在一些数字之后才能反映这个群体吗?在那种猜测中,接下来呢?

## Generate some example data
x = runif(5, 0, 300)
## Specify the labels
labels = c(0,25,75,125,175,225)
## Use cut as before
y = cut(x, 
    breaks = c(0,25,75,125,175,225,300),
    labels = labels,
    right = TRUE)
Run Code Online (Sandbox Code Playgroud)

当我们转换y为数字时,这将给出标签的索引。因此,

labels[as.numeric(y)]
Run Code Online (Sandbox Code Playgroud)

或更简单

labels[y]
Run Code Online (Sandbox Code Playgroud)

  • 实际上,最好保存中断,并且根本不使用标签-如果仅需要因子水平,则是否使用自动生成的标签都没关系。所以只是`df $ start &lt;-breaks [cut(df $ x,breaks = breaks,right = TRUE)]` (3认同)

小智 5

我会选择使用正则表达式,因为所有信息都在cut.

cut_borders <- function(x){
pattern <- "(\\(|\\[)(-*[0-9]+\\.*[0-9]*),(-*[0-9]+\\.*[0-9]*)(\\)|\\])"

start <- as.numeric(gsub(pattern,"\\2", x))
end <- as.numeric(gsub(pattern,"\\3", x))

data.frame(start, end)
}
Run Code Online (Sandbox Code Playgroud)

文字中的模式:

  • 第 1 组:a(或 a [,所以我们使用(\\(|\\[)

  • 第2组:数字可能为负数,所以我们( -*),我们要寻找至少一个[0-9]+可以有小数位的数字( ),即一个点( \\.*)和点( )之后的小数[0-9]*

  • 接下来有一个逗号 ( ,)

  • 第3组:与第2组相同。

  • 第 4 组:与第 1 组类似,我们期望 a)或 a ]

这是一些用分位数切割的随机变量。该函数cut_borders返回我们正在寻找的内容:

x <- rnorm(10)

x_groups <- cut(x, quantile(x, 0:4/4), include.lowest= TRUE)

cut_borders(x_groups)
Run Code Online (Sandbox Code Playgroud)