-7

Reproducible input:

df <- data.frame(
  "Date" = sprintf("%02d-Jan", 1:20),
  "Type of Weather" = c(rep("Cloudy", 3), rep("Rainy", 7), rep("Cloudy", 5), rep("Sunny", 5))
)
head(df)
     Date Type.of.Weather
1: 01-Jan          Cloudy
2: 02-Jan          Cloudy
3: 03-Jan          Cloudy
4: 04-Jan           Rainy
5: 05-Jan           Rainy
6: 06-Jan           Rainy

Expected output:

enter image description here

s_baldur
  • 29,441
  • 4
  • 36
  • 69
  • 2
    Hi Manav. Please spend some time reviewing [how to ask](https://stackoverflow.com/help/how-to-ask) questions here on SO, and then edit your post to provide a [minimal reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). We expect to see a decent amount of effort from you. That includes (1) giving your question a reasonable title, (2) having a clear problem statement, (3) sharing code and sample data in a reproducible way, and (4) showing your expected output. Screenshots are not useful. – Maurits Evers Jul 18 '18 at 12:23

1 Answers1

0

I would use data.table and do something like the following:

library(data.table)
setDT(df)
ndf <- df[, 
          .(Date = paste(Date[1], "to", Date[.N]), weather = Type.of.Weather[1]),
          rleid(Type.of.Weather)
          ][,
            rleid := NULL
           ][]
ndf
               Date weather
1: 01-Jan to 03-Jan  Cloudy
2: 04-Jan to 10-Jan   Rainy
3: 11-Jan to 15-Jan  Cloudy
4: 16-Jan to 20-Jan   Sunny
s_baldur
  • 29,441
  • 4
  • 36
  • 69
  • I want to add 2-3 more columns to this , 1 which takes the number of days in the date range, 2nd column calculates the average of rainfall in that date range or temperature, how should i do that using rleid() ? – Manvendra Shrimal Jul 23 '18 at 04:36