簡體   English   中英

如何在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))

我想根據每個xy的觀測值生成一個數字序列(例如,對於x=1 ,有y 2個觀測值)。 我希望序列不斷增加,並在每個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))

由於您現在具有順序的“新”重新調整,因此我們可以使用注釋中討論的邏輯。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM