Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading