data.table错误:数据没有存储到初始数据表中

问题描述 投票:0回答:1

这是我的代码:

Transactions_DT[, {
# Identify the rows where Unique_ID is not empty and not NA
  valid_rows <- which(Unique_ID != "" | !is.na(Unique_ID))
  
# Only process if there are valid rows
  if (length(valid_rows) > 0) {
# Calculate the cumulative sum of days to add starting from the first valid row
    days_to_add <- cumsum(Period_Length[valid_rows])
    
# Adjust the starting index for days to add to correctly apply days addition
# and offset by subtracting the first Period_Length because it's included twice (once in the initial date)
    Transaction_Date[valid_rows] <- Transaction_Date[valid_rows[1]] + days(days_to_add - Period_Length[valid_rows[1]])
  }
}, by = Con_ID]

然后我尝试做

:=
而不是
<-
,它根本没有帮助,R 告诉我这样做是不行的,我认为这是有道理的,因为向量的“大小”可以这么说...不知道如何解决。

r data.table
1个回答
0
投票

您可以考虑将逻辑包装在如下函数中:

f <- \(u,t,p) {
  v <- which(u != "" | !is.na(u))
  if(length(v)>0) {
    d <- cumsum(p[v])
    t[v] <- t[v[1]] + days(d - p[v[1]])
  }
  return(t)
}

然后应用你的函数,通过

Con_ID

Transactions_DT[, Transaction_Date:=f(Unique_ID, Transaction_Date, Period_Length), Con_ID]
© www.soinside.com 2019 - 2024. All rights reserved.