简体   繁体   English

有没有更有效的方法来计算 R 中的月份差异

[英]Is there a more efficient way to calculate the difference in months in R

I have a large data frame in a panel structure (201720 rows; 3 columns) which looks as follows:我在面板结构中有一个大数据框(201720 行;3 列),如下所示:

Name <- c("A", "A", "A", "B", "B", "B")

Inception <- c(as.Date("2007-12-31"), as.Date("2007-12-31"), as.Date("2007-12-31"),
               as.Date("1990-12-31"), as.Date("1990-12-31"), as.Date("1990-12-31"))
 
Months <- c(as.Date("2010-01-01"), as.Date("2010-02-01"), as.Date("2010-03-01"),
            as.Date("2010-01-01"), as.Date("2010-02-01"), as.Date("2010-03-01"))

df <- data.frame(Name, Inception, Months)

I want to calculate the difference in months of «Inception» and «Months» for each row and assign it to a new column named «Age».我想为每一行计算 «Inception» 和 «Months» 的月份差异,并将其分配给名为 «Age» 的新列。 If the result is negative, it should fill in with NA.如果结果为负,则应填写 NA。 I came up with the following solution and it worked.我想出了以下解决方案并且有效。 However, the computation of it is not very fast.但是,它的计算速度不是很快。

for (i in 1:nrow(df)){
  if(df[i,2]>df[i,3]){
    df[i,"Age"] <- NA
  } else {
    df[i,"Age"] <- interval(df[i,2],
                            df[i,3]) %/% months(1)
  }
}

Is there a more efficient way to calculate this difference?有没有更有效的方法来计算这种差异?

We can use case_when我们可以使用case_when

library(dplyr)
library(lubridate)
df <- df %>% 
  mutate(Age = case_when(Inception <= Months
     ~ interval(Inception, Months) %/% months(1)))

-output -输出

df
Name  Inception     Months Age
1    A 2007-12-31 2010-01-01  24
2    A 2007-12-31 2010-02-01  25
3    A 2007-12-31 2010-03-01  26
4    B 1990-12-31 2010-01-01 228
5    B 1990-12-31 2010-02-01 229
6    B 1990-12-31 2010-03-01 230

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM