【问题标题】:How to reference the current line while creating a new variable in a datatable in R如何在 R 的数据表中创建新变量时引用当前行
【发布时间】:2021-03-07 08:50:48
【问题描述】:

我想我已经不知不觉地在这个问题上徘徊了一段时间。

让我试着解释清楚。假设我有一个像这样的数据表:

library(tidyverse)
library(data.table)
library(lubridate)
MWE <- as.data.table(ggplot2::economics) %>%
  .[,c("pce","psavert","uempmed","unemploy"):=NULL]

> MWE
           date      pop
  1: 1967-07-01 198712.0
  2: 1967-08-01 198911.0
  3: 1967-09-01 199113.0
  4: 1967-10-01 199311.0
  5: 1967-11-01 199498.0
 ---                    
570: 2014-12-01 319746.2
571: 2015-01-01 319928.6
572: 2015-02-01 320074.5
573: 2015-03-01 320230.8
574: 2015-04-01 320402.3

我想做几件事,这意味着为给定行创建新变量 i 取决于该行的其他变量。

例如,如果我想要一个月到另一个月的人口演变,我想要的是这样的:

MWE2 &lt;- MWE[, MoM :=pop[date=i$date]/pop[date=(i$date-month(1))]

如果我想要年复一年的发展,也一样:

MWE3 &lt;- MWE[, YoY :=pop[date=i$date]/pop[date=(i$date-year(1))]

例如,如果我想创建前 5 年同一个月的当前值和人口平均值之间的差异,那将类似于

MWE4 &lt;- MWE[, 5YD :=pop- mean(pop[month(date)=month(i$date) &amp; (year(date$i)-6 &lt;= year(date) &lt; year(date$i))])]

那么有没有办法做一些接近我设想的事情? 如果我不清楚,请随时告诉我

【问题讨论】:

    标签: r datatable data-manipulation


    【解决方案1】:

    下面的代码块将为您提供数据集: 您可以对 MoM 和 YoY 变量主要使用 dplyrs 滞后函数。 MWE2 是一种获取月环比的方法,MWE3 获取 YoY 比率,最后 3 个数据集获取 5 年滞后并获取人口差异。 5 年代码可以根据需要更改为任何年份。

    library(tidyverse)
        library(data.table)
        library(lubridate)
    MWE <- as.data.table(ggplot2::economics) %>%
      .[,c("pce","psavert","uempmed","unemploy"):=NULL]
    MWE2 <- MWE %>% 
            arrange(date) %>% 
            mutate(
                   lagpop = lag(pop),
                   MoM = pop/lagpop)
    
    
    
    MWE3 <- MWE %>% 
      mutate(yeard = year(date)) %>% 
      group_by(yeard) %>% 
      summarise(avgpop = mean(pop,na.rm = TRUE)) %>% 
      ungroup %>% 
      arrange(yeard) %>% 
      mutate(lagpop = lag(avgpop),
             YoY = avgpop/lagpop)
    
    
    MWEa <- mutate(MWE, date5 = date+(365*5)+2 ,
                   yeard = year(date5),
                   monthd = month(date5))
    
    MWE <- mutate(MWE, 
                  yeard = year(date),
                  monthd = month(date))
    
    MWE4 <- left_join(MWE,MWEa , by = c("yeard","monthd")) %>% 
            mutate(diff5yr = pop.x - pop.y)
    

    【讨论】:

    • 我看到了使用 lag 的两个(次要)缺点:一个是我从每个组的第一个日期得到的值没有任何意义,第二个是我发现它有点复杂当我有更多变量时,请务必正确订购。我不再使用 R,但我相信 MWE3 计算的是全年的平均值,而我希望从前一年的同月开始每月增长
    • true,是的,该组的第一个值将是 NA,但该值可以更改。 MWE3 将计算全年,您想要滚动年平均值吗?您是否将其从R 移到另一个软件中?
    • 我指的是我一直在没有安装 R 的计算机上,而不是我改变了编程语言我的意思是,但我可能弄错了,正是每个组的第一个值(在我的真实数据中,我有几个组)不会是NA,但会有一个无意义的值。是的,我想我的意思是滚动年平均值
    • 好的,没问题,对于上面的第一点,如果您在使MWE2 的排列之前添加group_by(your_group),则第一个组值将为NA。这是滚动平均值的好资源:stackoverflow.com/questions/26198551/…
    【解决方案2】:

    回到基础。

    粗略的解决方案,但它很简单。

    library(data.table)
    library(lubridate)
    MWE <- as.data.table(ggplot2::economics)
    MWE <- MWE[,c("pce","psavert","uempmed","unemploy"):=NULL]
    data = data.frame(MWE)
    lubridate::month(MWE$date[1])
    
    
    monthly_diffs = double()
    yearly_diffs = double()
    current_year_months = 0
    current_year_sum = 0
    past_year_sum = 0
    past_year_months = 0
    
    
    for (i in 1:(nrow(data)-1)) {
      #since your data appears to be on a monthly basis, we can do the difference directly
      monthly_diffs[i] <- data$pop[i + 1] / data$pop[i]
      #for the years there is a need to accumulate it first.
      if (current_year_months == 0) {
        current_year <- year(MWE$date[i])
      }
      
      if (year(MWE$date[i]) == current_year) {
        #if we are within one year, we accumulate
        current_year_months <- current_year_months + 1
        current_year_sum <- current_year_sum + MWE$pop[i]
      } else {
        #otherwise we compute the averages, the ratio and save it
        if (past_year_months != 0) {
           #I will assume you want the average difference over the year
           #as I find it a reasonable approach to a yearly unemployment rates.
           #any other operation would be similar.
           current_year_average <- current_year_sum / current_year_months
           past_year_average <- past_year_sum / past_year_months 
           yearly_diffs = c(yearly_diffs, current_year_average / past_year_average)
           
        } 
        past_year_months = current_year_months
        past_year_sum = current_year_sum
        current_year_months = 0
        current_year_sum = 0
        current_year = year(MWE$date[i])
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2023-03-26
      • 2021-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多