R - DoD 更改的分组数据

R - Grouped data with DoD change

假设我有一个原始数据集(已经在数据框中,我可以使用 as.xts.data.table 轻松将其转换为 xts.data.table),DF 如下所示:

Date | City | State | Country | DailyMinTemperature | DailyMaxTemperature | DailyMedianTemperature
-------------------------
2018-02-03 | New York City | NY | US | 18 | 22 | 19
2018-02-03 | London | LDN |UK | 10 | 25 | 15
2018-02-03 | Singapore | SG | SG | 28 | 32 | 29
2018-02-02 | New York City | NY | US | 12 | 30 | 18
2018-02-02 | London | LDN | UK | 12 | 15 | 14
2018-02-02 | Singapore | SG | SG | 27 | 31 | 30

等等(更多的城市和更多的天数)。

我想让它显示当前一天的温度和与前一天相比的日间变化,以及城市(州、国家)的其他信息。即,新的数据框应该是这样的(来自上面的例子):

Date | City | State | Country | DailyMinTemperature | DailyMaxTemperature | DailyMedianTemperature| ChangeInDailyMin | ChangeInDailyMax | ChangeInDailyMedian
-------------------------
2018-02-03 | New York City | NY | US | 18 | 22 | 19 | 6 | -8 | 1
2018-02-03 | London | LDN |UK | 10 | 25 | 15 | -2 | -10 | 1
2018-02-03 | Singapore | SG | SG | 28 | 32 | 29 | 1 | 1 | -1
2018-02-03 | New York City | NY | US | ...

等等。即,再添加 3 列以显示每天的变化。

请注意,在数据框中我可能没有每天的数据,但是我的变化被定义为第 t 天的温度与我有温度数据的最近日期的温度之间的差异。

我尝试使用 shift 函数,但 R 抱怨 := 符号。

在 R 中有什么方法可以让它工作吗?

谢谢!

您可以使用 dplyr::mutate_atlubridate 包将数据转换为所需格式。数据需要按日期格式排列,可以借助dplyr::lag函数获取当前记录与上一条记录的差异。

library(dplyr)
library(lubridate)

df %>% mutate_if(is.character, funs(trimws)) %>%  #Trim any blank spaces
  mutate(Date = ymd(Date)) %>%                    #Convert to Date/Time
  group_by(City, State, Country) %>%               
  arrange(City, State, Country, Date) %>%         #Order data date
  mutate_at(vars(starts_with("Daily")), funs(Change = . - lag(.))) %>%
  filter(!is.na(DailyMinTemperature_Change))

结果:

# # A tibble: 3 x 10
# # Groups: City, State, Country [3]
# Date       City          State Country DailyMinTemperature DailyMaxTemperature DailyMedianTemperature DailyMinTemperature_Change DailyMaxT~ DailyMed~
#   <date>     <chr>         <chr> <chr>                 <dbl>               <dbl>                  <int>                      <dbl>      <dbl>     <int>
# 1 2018-02-03 London        LDN   UK                     10.0                25.0                     15                      -2.00      10.0          1
# 2 2018-02-03 New York City NY    US                     18.0                22.0                     19                       6.00     - 8.00         1
# 3 2018-02-03 Singapore     SG    SG                     28.0                32.0                     29                       1.00       1.00        -1
# 

数据:

df <- read.table(text = 
"Date | City | State | Country | DailyMinTemperature | DailyMaxTemperature | DailyMedianTemperature
2018-02-03 | New York City | NY | US | 18 | 22 | 19
2018-02-03 | London | LDN |UK | 10 | 25 | 15
2018-02-03 | Singapore | SG | SG | 28 | 32 | 29
2018-02-02 | New York City | NY | US | 12 | 30 | 18
2018-02-02 | London | LDN | UK | 12 | 15 | 14
2018-02-02 | Singapore | SG | SG | 27 | 31 | 30",
header = TRUE, stringsAsFactors = FALSE, sep = "|")