Meriem
Meriem

Reputation: 33

How to create a sequence from 2 columns of the same row

I have a data frame of 2 columns and a variable number of rows Example:

   E    P
1  0.5  1
2  2    2.5
3  3.5  4
.  .    .  
.  .    .
n  En   Pn

I want to create a data.frame from a sequence going from the first value of the column "E" to the first value of the column "P" by 0.1 and this is the code I did:

  rows_covering <<- data.frame(c(c1 = list (seq (E[1],P[1], 0.1)),
                                           c2 = list (seq (E[2],P[2], 0.1)),
                                           c3 = list (seq (E[3],P[3], 0.1))
                                            ))

However, as my number of rows is changing, it's not nice to change it every time manually especially for a big number of rows. Is it possible to do it automatically?

Upvotes: 1

Views: 345

Answers (4)

ThomasIsCoding
ThomasIsCoding

Reputation: 101099

A base R option is to use Map + seq

df <- within(df,rows_covering <- Map(seq,E,P,by = 0.1))

such that

> df
    E   P                rows_covering
1 0.5 1.0 0.5, 0.6, 0.7, 0.8, 0.9, 1.0
2 2.0 2.5 2.0, 2.1, 2.2, 2.3, 2.4, 2.5
3 3.5 4.0 3.5, 3.6, 3.7, 3.8, 3.9, 4.0

DATA

df <- structure(list(E = c(0.5, 2, 3.5), P = c(1, 2.5, 4)), class = "data.frame", row.names = c(NA, 
-3L))

> df
    E   P
1 0.5 1.0
2 2.0 2.5
3 3.5 4.0

Upvotes: 2

Marcelo Medre
Marcelo Medre

Reputation: 53

I think you have to use seq(E[x], P[x],0.1)

E <- c(0.5, 2, 3.5)
P <- c(1, 2.5, 4)
my_seq <- lapply(seq_along(E), function (x) (seq(E[x], P[x], 0.1)))

my_seq

Upvotes: 1

Allan Cameron
Allan Cameron

Reputation: 173793

You could try

lapply(seq_along(E), function(x) list(seq(E[x], P[x], 0.1)))

Upvotes: 3

Neel Kamal
Neel Kamal

Reputation: 1076

Tidy way...

df <- tibble(start = c(0.5, 0.2),
             end = c(1, 0.8))

df %>% mutate(seq = map2(start, end, ~seq(.x, .y, by = 0.1)))

Upvotes: 2

Related Questions