-4

R: I have data set that contains information of ticket: section, row, seat from, seat to, n.tickets. I want to create seat number using seat from and seat to variable, which will add more rows to my data. Example

data:  event , section , row, seat from , seat to, price, n.tickets
         1,       A,      10,    6,         8,      120,    3
mydata: event , section , row, seat number price, n.tickets
         1,       A,      10,    6,          120,    3
         1,       A,      10,    7,          120,    3
         1,       A,      10,    8,          120,    3

Mydata is the one that I would like to create. I tired rbind command in R but failed. I don't know if I need loops. Any help is much appreciated!

MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • 1
    Maybe you could show what you tried so we have some sort of starting point? – MrFlick Jun 26 '18 at 15:12
  • 1
    Jiadi Chen, the point here is that SO is not a free coding service, so we request that you show some effort to do what you need. A little research and ["elbow grease"](https://en.wikipedia.org/wiki/Elbow_grease) might provide your answer before needing to ask here, but will certainly give us a good place to start helping you. – r2evans Jun 26 '18 at 15:16

2 Answers2

0

Using base R you can do something like this

do.call("rbind", lapply(split(dd, 1:nrow(dd)), function(x) {
  data.frame(dd[1:3], seat=dd[1,4]:dd[1,5], dd[6:7])
}))

tested with

dd <- read.csv(text="event , section , row, seat from , seat to, price, n.tickets
1,       A,      10,    6,         8,      120,    3")

Here we split up the data.frame by rows, then create a new data.frame by expanding out the seat numbers, then we merge all the data.frames back together with do.call("rbind",...")

MrFlick
  • 195,160
  • 17
  • 277
  • 295
0

alternative:

dd <- read.csv(text="event , section , row, seat from , seat to, price, n.tickets
1,       A,      10,    6,         8,      120,    3")

seats = dd$seat.from:dd$seat.to
dd[seq_along(seats),] <- dd[1,]
dd %>% dplyr::select(-one_of("seat.from","seat.to")) %>% mutate(seats = seats)

#  event  section row price n.tickets seats
#1     1        A  10   120         3     6
#2     1        A  10   120         3     7
#3     1        A  10   120         3     8
Andre Elrico
  • 10,956
  • 6
  • 50
  • 69