如何在R中生成不均匀的数字序列
How to generate an uneven sequence of numbers in R
这是一个示例数据框:
df <- data.frame(x=c(1,1,2,2,2,3,3,4,5,6,6,6,9,9),y=c(1,2,3,4,6,3,7,8,6,4,3,7,3,2))
我想根据每个 x
组 y
的观察数生成一个数字序列(例如 x=1
有 2 个 y
的观察值).我希望序列在每个 x
组之后不断增加并跳转 2。
此示例所需的输出为:
1,2,5,6,7,10,11,14,17,20,21,22,25,26
我怎样才能在 R 中简单地做到这一点?
为了扩展我的评论,分组可以是任意的,您只需要将其重新转换为正确的顺序即可。有几种方法可以做到这一点,@akrun 已经表明可以使用 match
函数来完成,或者如果你自己更容易理解的话,你可以使用 as.numeric
函数。
df <- data.frame(x=c(1,1,2,2,2,3,3,4,5,6,6,6,9,9),y=c(1,2,3,4,6,3,7,8,6,4,3,7,3,2))
# these are equivalent
df$newx <- as.numeric(factor(df$x, levels=unique(df$x)))
df$newx <- match(df$x, unique(df$x))
由于您现在有一个 "new" 顺序的重新调平,我们可以使用评论中讨论的逻辑。
df$newNumber <- 1:nrow(df) + (df$newx-1)*2
对于此示例,这将导致以下数据帧:
x y newx newNumber
1 1 1 1
1 2 1 2
2 3 2 5
2 4 2 6
2 6 2 7
3 3 3 10
3 7 3 11
4 8 4 14
5 6 5 17
6 4 6 20
6 3 6 21
6 7 6 22
9 3 7 25
9 2 7 26
其中 df$newNumber
是您想要的输出。
要创建序列 0,0,4,4,4,9,...
,基本上您所做的就是取每组的最小值并减去 1
。最简单的方法是使用 library(dplyr)
.
library(dplyr)
df %>%
group_by(x) %>%
mutate(newNumber2 = min(newNumber) -1)
这将有输出:
Source: local data frame [14 x 5]
Groups: x
x y newx newNumber newNumber2
1 1 1 1 1 0
2 1 2 1 2 0
3 2 3 2 5 4
4 2 4 2 6 4
5 2 6 2 7 4
6 3 3 3 10 9
7 3 7 3 11 9
8 4 8 4 14 13
9 5 6 5 17 16
10 6 4 6 20 19
11 6 3 6 21 19
12 6 7 6 22 19
13 9 3 7 25 24
14 9 2 7 26 24
这是一个示例数据框:
df <- data.frame(x=c(1,1,2,2,2,3,3,4,5,6,6,6,9,9),y=c(1,2,3,4,6,3,7,8,6,4,3,7,3,2))
我想根据每个 x
组 y
的观察数生成一个数字序列(例如 x=1
有 2 个 y
的观察值).我希望序列在每个 x
组之后不断增加并跳转 2。
此示例所需的输出为:
1,2,5,6,7,10,11,14,17,20,21,22,25,26
我怎样才能在 R 中简单地做到这一点?
为了扩展我的评论,分组可以是任意的,您只需要将其重新转换为正确的顺序即可。有几种方法可以做到这一点,@akrun 已经表明可以使用 match
函数来完成,或者如果你自己更容易理解的话,你可以使用 as.numeric
函数。
df <- data.frame(x=c(1,1,2,2,2,3,3,4,5,6,6,6,9,9),y=c(1,2,3,4,6,3,7,8,6,4,3,7,3,2))
# these are equivalent
df$newx <- as.numeric(factor(df$x, levels=unique(df$x)))
df$newx <- match(df$x, unique(df$x))
由于您现在有一个 "new" 顺序的重新调平,我们可以使用评论中讨论的逻辑。
df$newNumber <- 1:nrow(df) + (df$newx-1)*2
对于此示例,这将导致以下数据帧:
x y newx newNumber
1 1 1 1
1 2 1 2
2 3 2 5
2 4 2 6
2 6 2 7
3 3 3 10
3 7 3 11
4 8 4 14
5 6 5 17
6 4 6 20
6 3 6 21
6 7 6 22
9 3 7 25
9 2 7 26
其中 df$newNumber
是您想要的输出。
要创建序列 0,0,4,4,4,9,...
,基本上您所做的就是取每组的最小值并减去 1
。最简单的方法是使用 library(dplyr)
.
library(dplyr)
df %>%
group_by(x) %>%
mutate(newNumber2 = min(newNumber) -1)
这将有输出:
Source: local data frame [14 x 5]
Groups: x
x y newx newNumber newNumber2
1 1 1 1 1 0
2 1 2 1 2 0
3 2 3 2 5 4
4 2 4 2 6 4
5 2 6 2 7 4
6 3 3 3 10 9
7 3 7 3 11 9
8 4 8 4 14 13
9 5 6 5 17 16
10 6 4 6 20 19
11 6 3 6 21 19
12 6 7 6 22 19
13 9 3 7 25 24
14 9 2 7 26 24