簡體   English   中英

時間序列:為子集編寫代碼的最有效方法是什么?

[英]Time series: What's the most efficient way to write code for subsets?

我有兩個數據框

DF1

time x   y   state
...  ... ... CA
...  ... ... MA
...  ... ... TX
...  ... ... MA
...  ... ... CA
...  ... ... IL

DF2

time x   y   state
...  ... ... MA
...  ... ... NY
...  ... ... MA
...  ... ... TX
...  ... ... CA
...  ... ... CA

然后,我有了一些代碼,在這些代碼中,我可以匯總每月值,重命名列,將數據與另一個列表進行匹配,然后將df1和df2合並為大約50行代碼中的一個。 到目前為止,我不考慮state

但是,我需要為幾個美國州創建合並數據框的子集。 除了復制/粘貼用於df1和df2的代碼並將df1和df2替換為df1_CA,df2_MA等之外,還有其他更優雅的方法嗎?

環? 面板數據?

一種選擇是使用data.table包進行分組分析。

# transform your data.frame to data.table
dt1 <- as.data.table(df1)
dt2 <- as.data.table(df2)

# e.g. grouping values on state level
dt1[, sum(y), by=state]
# this will accumulate all y values by state

如果您不想在代碼中替換df名稱,則可以定義一個函數:

# define the function
accumulate <- function(df){
  dt <- as.data.table(df)
  return(dt[, sum(y), by=state])
}

# and call it 
accumulate(df1)
accumulate(df2)

而不是在所有data.frames上使用for循環或類似方法,可以使用一種有效遍歷數據結構(例如列表)的apply函數之一

# alternatively define a list of data.frames and then iterate over the list
my.dfs <- list(df1,df2)
lapply(my.dfs, accumulate(df))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM