Home > Blockchain >  Create a sequence along the whole dataset increasing by certain number in R
Create a sequence along the whole dataset increasing by certain number in R

Time:09-22

How to create a new variable in the dataframe with a sequence increasing by 0.002, starting at 0 and running until the end of the dataset. I was attempting with:

dataset$seq = seq(0, length(dataset), by = 0.002)
dataset$seq = seq(0, nrow(dataset), by = 0.002)

But both throw an error about wrong lengths. Thanks for your help.

CodePudding user response:

Another option:

dataset$seq <- seq(0, by = 0.002, length.out = nrow(dataset))

CodePudding user response:

Does it work?

set.seed(123)
df <- data.frame(x = rnorm(10), y = rnorm(10), z = rnorm(10))
df$seq <- seq(0, 0.002 * (nrow(df) - 1), 0.002)

             x          y          z   seq
1  -0.56047565  1.2240818 -1.0678237 0.000
2  -0.23017749  0.3598138 -0.2179749 0.002
3   1.55870831  0.4007715 -1.0260044 0.004
4   0.07050839  0.1106827 -0.7288912 0.006
5   0.12928774 -0.5558411 -0.6250393 0.008
6   1.71506499  1.7869131 -1.6866933 0.010
7   0.46091621  0.4978505  0.8377870 0.012
8  -1.26506123 -1.9666172  0.1533731 0.014
9  -0.68685285  0.7013559 -1.1381369 0.016
10 -0.44566197 -0.4727914  1.2538149 0.018

CodePudding user response:

One way:

library(dplyr)

df %>% mutate(seq = rep(.002, nrow(df)) * 1:nrow(df))
   col1 col2   seq
1     a    1 0.002
2     b    2 0.004
3     c    3 0.006
4     d    4 0.008
5     e    5 0.010
6     f    6 0.012
7     g    7 0.014
8     h    8 0.016
9     i    9 0.018
10    j   10 0.020

Sure:

df %>% mutate(seq = rep(.002, nrow(df)) * 1:nrow(df) - .002)
   col1 col2   seq
1     a    1 0.000
2     b    2 0.002
3     c    3 0.004
4     d    4 0.006
5     e    5 0.008
6     f    6 0.010
7     g    7 0.012
8     h    8 0.014
9     i    9 0.016
10    j   10 0.018
  • Related