主頁 > .NET開發 > 在資料幀1中包含來自其他幾個資料幀的平均值,并基于不同的時間間隔

在資料幀1中包含來自其他幾個資料幀的平均值,并基于不同的時間間隔

2021-11-20 16:58:05 .NET開發

我有一個包含多個變數的資料框,其第一列如下所示:

Place <- c(rep("PlaceA",14),rep("PlaceB",15))
Group_Id <- c(rep("A1",5),rep("A1",6),rep("A2",3),rep("B1",6),rep("B2",4),rep("B2",5))
Time <- as.Date(c("2018-01-15","2018-02-03","2018-02-27","2018-03-10","2018-03-18","2019-02-02","2019-03-01","2019-03-15","2019-03-28","2019-04-05","2019-04-12","2018-02-01",
                  "2018-03-01","2018-04-07","2018-01-17","2018-01-27","2018-02-17","2018-03-03","2018-04-02","2018-04-25","2018-03-03","2018-03-18","2018-04-08","2018-04-20",
                  "2019-01-23","2019-02-09","2019-02-27","2019-03-12","2019-03-30"))
FollowUp <- c("start",paste("week",week(ymd(Time[2:5]))),"start",paste("week",week(ymd(Time[7:11]))),"start",paste("week",week(ymd(Time[13:14]))),"start",paste("week",week(ymd(Time[16:20]))),"start",paste("week",week(ymd(Time[22:24]))),"start",paste("week",week(ymd(Time[26:29]))))
exprmt <- c(rep(1,5),rep(2,6),rep(3,3),rep(4,6),rep(5,4),rep(6,5))

> df1
    Place Group_Id       Time exprmt FollowUp
1  PlaceA       A1 2018-01-15      1    start
2  PlaceA       A1 2018-02-03      1   week 5
3  PlaceA       A1 2018-02-27      1   week 9
4  PlaceA       A1 2018-03-10      1  week 10
5  PlaceA       A1 2018-03-18      1  week 11
6  PlaceA       A1 2019-02-02      2    start
7  PlaceA       A1 2019-03-01      2   week 9
8  PlaceA       A1 2019-03-15      2  week 11
9  PlaceA       A1 2019-03-28      2  week 13
10 PlaceA       A1 2019-04-05      2  week 14
11 PlaceA       A1 2019-04-12      2  week 15
12 PlaceA       A2 2018-02-01      3    start
13 PlaceA       A2 2018-03-01      3   week 9
14 PlaceA       A2 2018-04-07      3  week 14
15 PlaceB       B1 2018-01-17      4    start
16 PlaceB       B1 2018-01-27      4   week 4
17 PlaceB       B1 2018-02-17      4   week 7
18 PlaceB       B1 2018-03-03      4   week 9
19 PlaceB       B1 2018-04-02      4  week 14
20 PlaceB       B1 2018-04-25      4  week 17
21 PlaceB       B2 2018-03-03      5    start
22 PlaceB       B2 2018-03-18      5  week 11
23 PlaceB       B2 2018-04-08      5  week 14
24 PlaceB       B2 2018-04-20      5  week 16
25 PlaceB       B2 2019-01-23      6    start
26 PlaceB       B2 2019-02-09      6   week 6
27 PlaceB       B2 2019-02-27      6   week 9
28 PlaceB       B2 2019-03-12      6  week 11
29 PlaceB       B2 2019-03-30      6  week 13

對于每個地方(在我的實際資料中超過 2 個),我有一個單獨的資料框,其中包含按小時計算的溫度記錄。例如:

set.seed(1032)
t <- c(seq.POSIXt(from = ISOdate(2018,01,01),to = ISOdate(2018,06,01), by = "hour"),seq.POSIXt(from = ISOdate(2019,01,01),to = ISOdate(2019,06,01), by = "hour"))
temp_A <- runif(length(t),min = 5, max = 25)
temp_B <- runif(length(t),min = 3, max = 32)
data_A <- data.frame(t,temp_A)
data_B <- data.frame(t,temp_B)

> head(data_A)
                    t   temp_A
1 2018-01-01 12:00:00 14.24961
2 2018-01-01 13:00:00 21.64925
3 2018-01-01 14:00:00 21.77058
4 2018-01-01 15:00:00 13.31673
5 2018-01-01 16:00:00 16.10350
6 2018-01-01 17:00:00 17.64567

我需要df1在時間間隔內按 Place、group_Id 和 exrmt添加一列平均溫度:每個的第一個group_by應該是 NaN,而不是我需要每個時間間隔的平均值。知道對于每個地方,資料也在一個單獨的資料框中。

我試過這樣的事情,但它不起作用:

df1 <- df1 %>% group_by(Place,Group_Id,exprmt) %>% mutate(
  temp = case_when(FollowUp == "start" & Place == "PlaceA" ~ NA,
                   FollowUp == FollowUp[c(2:n())] & Place == "PlaceA" ~ mean(temp_A[c(which(date(temp_A$t))==lag(Time,1):which(date(temp_A$t))==Time),2]),
                   )
)

我找到了有關如何計算多個資料幀(例如thisthis)的平均值的資訊,但這不是我要找的。我想在沒有回圈的情況下做到這一點。我的預期結果是(等代表等等..):

> df1
    Place Group_Id       Time exprmt FollowUp                                      expected
1  PlaceA       A1 2018-01-15      1    start                                           NaN
2  PlaceA       A1 2018-02-03      1   week 5 mean temp_A between 2018-01-15 and 2018-02-03
3  PlaceA       A1 2018-02-27      1   week 9 mean temp_A between 2018-02-03 and 2018-02-27
4  PlaceA       A1 2018-03-10      1  week 10 mean temp_A between 2018-02-27 and 2018-03-10
5  PlaceA       A1 2018-03-18      1  week 11 mean temp_A between 2018-03-10 and 2018-03-18
6  PlaceA       A1 2019-02-02      2    start                                           NaN
7  PlaceA       A1 2019-03-01      2   week 9 mean temp_A between 2019-02-02 and 2019-03-01
8  PlaceA       A1 2019-03-15      2  week 11                                           etc
9  PlaceA       A1 2019-03-28      2  week 13                                           etc
10 PlaceA       A1 2019-04-05      2  week 14                                           etc
11 PlaceA       A1 2019-04-12      2  week 15                                           etc
12 PlaceA       A2 2018-02-01      3    start                                           etc
13 PlaceA       A2 2018-03-01      3   week 9                                           etc
14 PlaceA       A2 2018-04-07      3  week 14                                           etc
15 PlaceB       B1 2018-01-17      4    start                                           NaN
16 PlaceB       B1 2018-01-27      4   week 4 mean temp_B between 2018-01-17 and 2018-01-27
17 PlaceB       B1 2018-02-17      4   week 7                                           etc
18 PlaceB       B1 2018-03-03      4   week 9                                           etc
19 PlaceB       B1 2018-04-02      4  week 14                                           etc
20 PlaceB       B1 2018-04-25      4  week 17                                           etc
21 PlaceB       B2 2018-03-03      5    start                                           etc
22 PlaceB       B2 2018-03-18      5  week 11                                           etc
23 PlaceB       B2 2018-04-08      5  week 14                                           etc
24 PlaceB       B2 2018-04-20      5  week 16                                           etc
25 PlaceB       B2 2019-01-23      6    start                                           etc
26 PlaceB       B2 2019-02-09      6   week 6                                           etc
27 PlaceB       B2 2019-02-27      6   week 9                                           etc
28 PlaceB       B2 2019-03-12      6  week 11                                           etc
29 PlaceB       B2 2019-03-30      6  week 13                                           etc

任何幫助將不勝感激!

uj5u.com熱心網友回復:

我建議一個詳細的分步解決方案(使用data.tablelubridate庫),可能有點學術性,但盡量不失去讀者。所以,請在下面找到一個reprex。

正品

1. 資料準備

library(data.table)
library(lubridate)

# Convert the dataframe 'df1' into data.table and add the dummy variable 'StartTime' 
setDT(df1)[, StartTime := shift(Time,1), by = .(Place, Group_Id, exprmt)][]
setcolorder(df1, c("Place", "Group_Id", "FollowUp", "exprmt", "StartTime", "Time"))

# What df1 looks like:
df1
#>      Place Group_Id FollowUp exprmt  StartTime       Time
#>  1: PlaceA       A1    start      1       <NA> 2018-01-15
#>  2: PlaceA       A1   week 5      1 2018-01-15 2018-02-03
#>  3: PlaceA       A1   week 9      1 2018-02-03 2018-02-27
#>  4: PlaceA       A1  week 10      1 2018-02-27 2018-03-10
#>  5: PlaceA       A1  week 11      1 2018-03-10 2018-03-18
#>  6: PlaceA       A1    start      2       <NA> 2019-02-02
#>  7: PlaceA       A1   week 9      2 2019-02-02 2019-03-01
#>  8: PlaceA       ....


# Convert 'StartTime' and 'Time' columns into class 'PosiXct'
sel_cols <- c("StartTime", "Time")
df1[, (sel_cols) := lapply(.SD, as.POSIXct, tz = "GMT"), .SDcols = sel_cols]

# Convert the dataframes 'data_A' and 'data_B' into data.tables
setDT(data_A)
setDT(data_B)

2. 加入

# Merge 'data_A' and 'data_B' on 't'
data_merge <- merge(data_A, data_B, by = 't')

# Join 'df1' and 'data_merge' with Time > t >= StartTime, and remove unnecessary columns
DF_join_1 <- df1[data_merge, on = .(StartTime <= t,Time > t)
                 ][, `:=` (Place = NULL, Group_Id = NULL, FollowUp = NULL, exprmt = NULL, Time = NULL)
                   ][]

# Join 'DF_join_1' and 'df1' on StartTime, then remove the dummy variable StartTime and reorder columns
DF_join_2 <- DF_join_1[df1, on = .(StartTime)
                       ][, StartTime := NULL
                         ][]

setcolorder(DF_join_2, c("Place", "Group_Id", "Time", "exprmt", "FollowUp", "temp_A", "temp_B"))

3. 添加一列“TEMP”

# Create a column 'temp' filled with 'temp_A' values when 'Place == PlaceA' and 'temp_B' values when 'Place == PlaceB'
DF_results <- DF_join_2[, temp := fcase(Place == "PlaceA", temp_A,
                                        Place == "PlaceB", temp_B)
                        ][, `:=` (temp_A = NULL, temp_B = NULL)
                          ][]

4. 總結以獲得所需的輸出

# Summarize DF_results to get the mean of 'temp' by group in the 'expected' variable
DF_results[, .(expected = mean(temp, na.rm = TRUE)), by = .(Place, Group_Id, exprmt, Time, FollowUp)]
#>      Place Group_Id exprmt       Time FollowUp  expected
#>  1: PlaceA       A1      1 2018-01-15    start       NaN
#>  2: PlaceA       A1      1 2018-02-03   week 5 10.618465
#>  3: PlaceA       A1      1 2018-02-27   week 9 15.997990
#>  4: PlaceA       A1      1 2018-03-10  week 10 14.874170
#>  5: PlaceA       A1      1 2018-03-18  week 11  8.005203
#>  6: PlaceA       A1      2 2019-02-02    start       NaN
#>  7: PlaceA       A1      2 2019-03-01   week 9 17.768572
#>  8: PlaceA       A1      2 2019-03-15  week 11  8.525002
#>  9: PlaceA       A1      2 2019-03-28  week 13 20.948760
#> 10: PlaceA       A1      2 2019-04-05  week 14 16.898529
#> 11: PlaceA       A1      2 2019-04-12  week 15  7.172799
#> 12: PlaceA       A2      3 2018-02-01    start       NaN
#> 13: PlaceA       A2      3 2018-03-01   week 9 17.521202
#> 14: PlaceA       A2      3 2018-04-07  week 14 21.653708
#> 15: PlaceB       B1      4 2018-01-17    start       NaN
#> 16: PlaceB       B1      4 2018-01-27   week 4 22.622165
#> 17: PlaceB       B1      4 2018-02-17   week 7 22.462456
#> 18: PlaceB       B1      4 2018-03-03   week 9 10.210829
#> 19: PlaceB       B1      4 2018-04-02  week 14 19.731544
#> 20: PlaceB       B1      4 2018-04-25  week 17 25.700109
#> 21: PlaceB       B2      5 2018-03-03    start       NaN
#> 22: PlaceB       B2      5 2018-03-18  week 11 19.731544
#> 23: PlaceB       B2      5 2018-04-08  week 14 16.757186
#> 24: PlaceB       B2      5 2018-04-20  week 16  5.248006
#> 25: PlaceB       B2      6 2019-01-23    start       NaN
#> 26: PlaceB       B2      6 2019-02-09   week 6  7.720195
#> 27: PlaceB       B2      6 2019-02-27   week 9 13.185666
#> 28: PlaceB       B2      6 2019-03-12  week 11  9.706857
#> 29: PlaceB       B2      6 2019-03-30  week 13 10.022071
#>      Place Group_Id exprmt       Time FollowUp  expected

reprex 包(v2.0.1)于 2021 年 11 月 19 日創建

uj5u.com熱心網友回復:

與 2 個地方的溫度資料共享結果。您始終可以通過連接和創建單個資料物件(如果總位置較少)或使用 ifelse 陳述句來概括相同的內容。

library(data.table)
setDT(df1)
setDT(data_A) # converting to data.table
setDT(data_B) # converting to data.table

合并溫度以具有單個資料物件

data_AB <- merge(data_A, data_B, by = 't')

根據 Place、Group_Id、exprmt 創建 Time 變數的滯后列

df1[,':='(LAG_DATE = shift(Time, type = 'lag')), by = .(Place, Group_Id, exprmt)]

使用應用函式和用戶定義函式根據連續時間段對溫度資料進行子集化,并使用 data.table 功能和 lapply 來獲取這些子集的平均值

在這里,我假設 Place 列可以在某些條件下與溫度資料以某種方式連接/映射。就像示例中的共享 temp_A/temp_B 可以通過連接“temp_”和 Place 列的第 6 個字符來形成

df1[,':='(EXPECTED = apply(cbind(LAG_DATE, Time, Place), 1, function(x) {
x1 <- as.Date(as.numeric(x[1]), origin = '1970-01-01')
x2 <- as.Date(as.numeric(x[2]), origin = '1970-01-01')
Place <- as.character(x[3])
Mean_Value <- ifelse(is.na(x1), NaN, data_AB[as.Date(t) >= x1 & 
as.Date(t) <= x2, lapply(.SD, mean), .SDcols = paste('temp_', substr(Place, 6, 
6), sep = '')])
return(as.numeric(Mean_Value))
}
))]

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/360935.html

標籤:r 数据框 dplyr 整理宇宙

上一篇:將帶逗號的文本檔案轉換為1列CSV

下一篇:基于切片更新熊貓資料框?

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • WebAPI簡介

    Web體系結構: 有三個核心:資源(resource),URL(統一資源識別符號)和表示 他們的關系是這樣的:一個資源由一個URL進行標識,HTTP客戶端使用URL定位資源,表示是從資源回傳資料,媒體型別是資源回傳的資料格式。 接下來我們說下HTTP. HTTP協議的系統是一種無狀態的方式,使用請求/ ......

    uj5u.com 2020-09-09 22:07:47 more
  • asp.net core 3.1 入口:Program.cs中的Main函式

    本文分析Program.cs 中Main()函式中代碼的運行順序分析asp.net core程式的啟動,重點不是剖析原始碼,而是理清程式開始時執行的順序。到呼叫了哪些實體,哪些法方。asp.net core 3.1 的程式入口在專案Program.cs檔案里,如下。ususing System; us ......

    uj5u.com 2020-09-09 22:07:49 more
  • asp.net網站作為websocket服務端的應用該如何寫

    最近被websocket的一個問題困擾了很久,有一個需求是在web網站中搭建websocket服務。客戶端通過網頁與服務器建立連接,然后服務器根據ip給客戶端網頁發送資訊。 其實,這個需求并不難,只是剛開始對websocket的內容不太了解。上網搜索了一下,有通過asp.net core 實作的、有 ......

    uj5u.com 2020-09-09 22:08:02 more
  • ASP.NET 開源匯入匯出庫Magicodes.IE Docker中使用

    Magicodes.IE在Docker中使用 更新歷史 2019.02.13 【Nuget】版本更新到2.0.2 【匯入】修復單列匯入的Bug,單元測驗“OneColumnImporter_Test”。問題見(https://github.com/dotnetcore/Magicodes.IE/is ......

    uj5u.com 2020-09-09 22:08:05 more
  • 在webform中使用ajax

    如果你用過Asp.net webform, 說明你也算是.NET 開發的老兵了。WEBform應該是2011 2013左右,當時還用visual studio 2005、 visual studio 2008。后來基本都用的是MVC。 如果是新開發的專案,估計沒人會用webform技術。但是有些舊版 ......

    uj5u.com 2020-09-09 22:08:50 more
  • iis添加asp.net網站,訪問提示:由于擴展配置問題而無法提供您請求的

    今天在iis服務器配置asp.net網站,遇到一個問題,記錄一下: 問題:由于擴展配置問題而無法提供您請求的頁面。如果該頁面是腳本,請添加處理程式。如果應下載檔案,請添加 MIME 映射。 WindowServer2012服務器,添加角色安裝完.netframework和iis之后,運行aspx頁面 ......

    uj5u.com 2020-09-09 22:10:00 more
  • WebAPI-處理架構

    帶著問題去思考,大家好! 問題1:HTTP請求和回傳相應的HTTP回應資訊之間發生了什么? 1:首先是最底層,托管層,位于WebAPI和底層HTTP堆疊之間 2:其次是 訊息處理程式管道層,這里比如日志和快取。OWIN的參考是將訊息處理程式管道的一些功能下移到堆疊下端的OWIN中間件了。 3:控制器處理 ......

    uj5u.com 2020-09-09 22:11:13 more
  • 微信門戶開發框架-使用指導說明書

    微信門戶應用管理系統,采用基于 MVC + Bootstrap + Ajax + Enterprise Library的技術路線,界面層采用Boostrap + Metronic組合的前端框架,資料訪問層支持Oracle、SQLServer、MySQL、PostgreSQL等資料庫。框架以MVC5,... ......

    uj5u.com 2020-09-09 22:15:18 more
  • WebAPI-HTTP編程模型

    帶著問題去思考,大家好!它是什么?它包含什么?它能干什么? 訊息 HTTP編程模型的核心就是訊息抽象,表示為:HttPRequestMessage,HttpResponseMessage.用于客戶端和服務端之間交換請求和回應訊息。 HttpMethod類包含了一組靜態屬性: private stat ......

    uj5u.com 2020-09-09 22:15:23 more
  • 部署WebApi隨筆

    一、跨域 NuGet參考Microsoft.AspNet.WebApi.Cors WebApiConfig.cs中配置: // Web API 配置和服務 config.EnableCors(new EnableCorsAttribute("*", "*", "*")); 二、清除默認回傳XML格式 ......

    uj5u.com 2020-09-09 22:15:48 more
最新发布
  • C#多執行緒學習(二) 如何操縱一個執行緒

    <a href="https://www.cnblogs.com/x-zhi/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/2943582/20220801082530.png" alt="" /></...

    uj5u.com 2023-04-19 09:17:20 more
  • C#多執行緒學習(二) 如何操縱一個執行緒

    C#多執行緒學習(二) 如何操縱一個執行緒 執行緒學習第一篇:C#多執行緒學習(一) 多執行緒的相關概念 下面我們就動手來創建一個執行緒,使用Thread類創建執行緒時,只需提供執行緒入口即可。(執行緒入口使程式知道該讓這個執行緒干什么事) 在C#中,執行緒入口是通過ThreadStart代理(delegate)來提供的 ......

    uj5u.com 2023-04-19 09:16:49 more
  • 記一次 .NET某醫療器械清洗系統 卡死分析

    <a href="https://www.cnblogs.com/huangxincheng/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/214741/20200614104537.png" alt="" /&g...

    uj5u.com 2023-04-18 08:39:04 more
  • 記一次 .NET某醫療器械清洗系統 卡死分析

    一:背景 1. 講故事 前段時間協助訓練營里的一位朋友分析了一個程式卡死的問題,回過頭來看這個案例比較經典,這篇稍微整理一下供后來者少踩坑吧。 二:WinDbg 分析 1. 為什么會卡死 因為是表單程式,理所當然就是看主執行緒此時正在做什么? 可以用 ~0s ; k 看一下便知。 0:000> k # ......

    uj5u.com 2023-04-18 08:33:10 more
  • SignalR, No Connection with that ID,IIS

    <a href="https://www.cnblogs.com/smartstar/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/u36196.jpg" alt="" /></a>...

    uj5u.com 2023-03-30 17:21:52 more
  • 一次對pool的誤用導致的.net頻繁gc的診斷分析

    <a href="https://www.cnblogs.com/dotnet-diagnostic/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/3115652/20230225090434.png" alt=""...

    uj5u.com 2023-03-28 10:15:33 more
  • 一次對pool的誤用導致的.net頻繁gc的診斷分析

    <a href="https://www.cnblogs.com/dotnet-diagnostic/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/3115652/20230225090434.png" alt=""...

    uj5u.com 2023-03-28 10:13:31 more
  • C#遍歷指定檔案夾中所有檔案的3種方法

    <a href="https://www.cnblogs.com/xbhp/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/957602/20230310105611.png" alt="" /></a&...

    uj5u.com 2023-03-27 14:46:55 more
  • C#/VB.NET:如何將PDF轉為PDF/A

    <a href="https://www.cnblogs.com/Carina-baby/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/2859233/20220427162558.png" alt="" />...

    uj5u.com 2023-03-27 14:46:35 more
  • 武裝你的WEBAPI-OData聚合查詢

    <a href="https://www.cnblogs.com/podolski/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/616093/20140323000327.png" alt="" /><...

    uj5u.com 2023-03-27 14:46:16 more