Home > Back-end >  R create a dataframe with discrete steps based on a range?
R create a dataframe with discrete steps based on a range?

Time:06-10

Hi supposed I have a range from 0-112 and I want to create a dataframe with steps= 20, for example, ideally I can set step =20 and it would return,

V1 V2
0  20
20 40
40 60
60 80
80 100
100 112

I can do this with a loop and built the dataframe row by row until it reaches the max, but wondering if there is a more efficient/cleaner way to do this?

thanks in advance.

CodePudding user response:

We can use seq to create the first vector, then remove the first element from the vector while concatenating the 112 at the end to create the second vector and then construct the data.frame with the two vectors

V1 <- seq(0, 112, by = 20)
V2 <- c(V1[-1], 112)
data.frame(V1, V2)

-output

   V1  V2
1   0  20
2  20  40
3  40  60
4  60  80
5  80 100
6 100 112

Or in a single step

within(data.frame(V1 = 0:5 * 20), V2 <- c(V1[-1], 112))
   V1  V2
1   0  20
2  20  40
3  40  60
4  60  80
5  80 100
6 100 112
  •  Tags:  
  • r
  • Related