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

问题描述 投票:7回答:3

我在这里看过这个问题。将数值按区间分组

然而,我想输出一个数值(而不是系数),特别是下界和上界的数值(分栏)。

实质上,这是对的,只是'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)

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

谢谢!我在这里看到了这个问题。

r cut
3个回答
7
投票

我猜测你想要什么,因为如果你想要 "原始数字",你可以直接使用 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)

当我们把 y 到一个数字,这就给出了标签的索引。因此。

labels[as.numeric(y)]

或更简单

labels[y]

9
投票

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

你会从数据开始

set.seed(17)
df <- data.frame(x=300 * runif(100))

然后设置断点,找到间隔。

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]

0
投票

我会选择使用regex,因为所有的信息都在输出中。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)
}

字的模式。

  • 第1组:要么是 ([因此,我们使用 (\\(|\\[).

  • 第二组:数字可能是负数,所以我们(-*),我们正在寻找至少一个数字([0-9]+),它可以有小数点,即一个点(\\.*)和点后小数([0-9]*).

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

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

  • 第4组:类似于第1组,我们希望有一个 )].

这里是一些随机变量与量子化切割。函数 cut_borders 返回我们要找的东西。

x <- rnorm(10)

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

cut_borders(x_groups)
© www.soinside.com 2019 - 2024. All rights reserved.