如何创建一个新变量,将数值变量分配给 1000 个单位的间隔。 R
How to make a new variable that assigns a numeric variable to intervals of 1000 units. R
在数据框中,我有变量 position,范围从 0 到 2.7M。
我想创建一个新变量 bin 取值 position 并将其分配给 1000 的间隔:
- 从 1 到 1000 -> 1000
- 从 1001 到 2000 -> 2000
- 从 2001 到 3000 -> 3000
- 等等
position
bin
128
1000
333
1000
2900
3000
4444
5000
我看了之前的问题,没找到解决办法。
提前致谢。
你可以做到
bin <- 1000 * ceiling(position / 1000)
你可以使用
df$bin_2 <- (df$position %/% 1000 + 1) * 1000
您可以使用 cut
:
library(dplyr)
bin_size <- 1000
bin_seq <- seq(0, ceiling(max(df$position)/bin_size)*bin_size, bin_size)
df %>%
mutate(bin = cut(
position,
bin_seq,
include.lowest = TRUE,
labels = bin_seq[-1]
))
输出
position bin
1 128 1000
2 333 1000
3 2900 3000
4 4444 5000
数据
df <-structure(list(position = c(128L, 333L, 2900L, 4444L)), class = "data.frame", row.names = c(NA,
-4L))
在数据框中,我有变量 position,范围从 0 到 2.7M。
我想创建一个新变量 bin 取值 position 并将其分配给 1000 的间隔:
- 从 1 到 1000 -> 1000
- 从 1001 到 2000 -> 2000
- 从 2001 到 3000 -> 3000
- 等等
position | bin |
---|---|
128 | 1000 |
333 | 1000 |
2900 | 3000 |
4444 | 5000 |
我看了之前的问题,没找到解决办法。
提前致谢。
你可以做到
bin <- 1000 * ceiling(position / 1000)
你可以使用
df$bin_2 <- (df$position %/% 1000 + 1) * 1000
您可以使用 cut
:
library(dplyr)
bin_size <- 1000
bin_seq <- seq(0, ceiling(max(df$position)/bin_size)*bin_size, bin_size)
df %>%
mutate(bin = cut(
position,
bin_seq,
include.lowest = TRUE,
labels = bin_seq[-1]
))
输出
position bin
1 128 1000
2 333 1000
3 2900 3000
4 4444 5000
数据
df <-structure(list(position = c(128L, 333L, 2900L, 4444L)), class = "data.frame", row.names = c(NA,
-4L))