按R中的日期汇总data.frame

时间:2018-07-18 11:36:12

标签: r

可重复输入:

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

预期输出:

enter image description here

1 个答案:

答案 0 :(得分:0)

我将使用data.table并执行以下操作:

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