Search code examples
rdplyrseq

Create column in R that increments every row to length of dataframe


I would like to add a column to my dataframe that starts at 0 and increments 0.002 every row till the end of the dataframe.

I tried:

NewCol <- seq(0,len(DF),0.002))
DF <- cbind(DF, NewCol)

My desired output would be: 0.00 0.002 0.004 0.006 ...to the end of the dataframe

The NewCol length was too long to cbind to my dataframe.


Solution

  • We can use nrow for this inside the seq function like so

    df <- data.frame(a = c(1:5), b = 6:10)
      a b
    1 1 o
    2 2 c
    3 3 p
    4 4 u
    5 5 d
    
    df$num = seq(0, by = 0.002, to = nrow(df)*0.002 - 0.002)
    
    # simplified by @Ritchie Sacramento to
    
    df$num = seq(0, by = 0.002, length.out = nrow(df))
    
      a b   num
    1 1 o 0.000
    2 2 c 0.002
    3 3 p 0.004
    4 4 u 0.006
    5 5 d 0.008