maximusdooku - 4 months ago 15

R Question

`structure(list(Time = structure(c(1080827100, 1080827400, 1080827700,`

1080828000, 1080828300, 1080828600, 1080828900, 1080829200, 1080829500,

1080829800), class = c("POSIXct", "POSIXt"), tzone = "UTC"),

precip = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0.02)), .Names = c("Time",

"precip"), row.names = 236614:236623, class = "data.frame")

I want to add the precip with a sequence of numbers that are odd multiples of 2.5

`p1*2.5 + p2*7.5+ p3*12.5 +...`

Where p1,p2,p3 are rows of precip.

How can I generate this sequence of numbers (2.5, 7.5, 12.5, 17.5 etc) based on length of dataframe and add it as additional column in the same dataframe?

I tried:

`df$new <-seq(0,nrow(df),2.5)`

This is wrong ofcourse. I need to be able to mention the number of values I want instead of the last value using nrow(df).

Answer

Here's one way:

```
remove <- seq(0,100, 2.5)
nums <- remove[c(F, T)]
nums <- nums[1:nrow(df1)]
df1$new <- nums
```

Note if you know the number of elements you want then you can replace `100`

with that (or 2x that, actually) and skip the 3rd line. Otherwise `100`

is an arbitrary large number.

So a variation would be

```
remove <- seq(0,50, 2.5)
nums <- remove[c(F, T)]
df1$new <- nums
```

or, as mentioned in the comments, you could do

```
seq(2.5, length.out = nrow(df), by = 5)
```

actually, we can improve this slightly as `length.out`

is unncessary:

```
df1$new <- seq(2.5, nrow(df1), by = 5)
```