我有一個資料框,其中包含來自各種設備的記錄,這些設備測量溫度和濕度等引數,我試圖以 10 分鐘的間隔對記錄進行分組。有問題的例子:
id datetime hum temp room
<chr> <S3: POSIXct> <dbl> <dbl> <chr>
AA 2021-11-26 18:49:34 31 24 living room
AA 2021-11-26 18:54:34 29 26 living room
BB 2021-11-26 18:49:34 31 24 bathroom
BB 2021-11-26 18:54:34 33 23 bathroom
我的代碼是:
test %>%
group_by(id, datetime = cut(datetime, "10 min")) %>%
summarise(across(hum:temp, ~ mean(.x)))
如何在匯總其他變數的同時保留房間變數(以及本示例中沒有的其他變數)?
想要的結果:
id datetime hum temp room
<chr> <S3: POSIXct> <dbl> <dbl> <chr>
AA 2021-11-26 18:49:00 30 25 living room
BB 2021-11-26 18:49:00 32 23.5 bathroom
我唯一的想法是先洗掉其他變數,然后再將它們加入,但我認為可能有更簡單的方法。
uj5u.com熱心網友回復:
你的意思是這樣的:只需room在該行中添加或其他內容group_by:
df %>%
mutate(datetime = as.POSIXct(datetime)) %>% # This you may not need
group_by(id, datetime = cut(datetime, "10 min"), room) %>%
summarise(across(hum:temp, ~ mean(.x)), .groups = "keep")
id datetime room hum temp
<chr> <fct> <chr> <dbl> <dbl>
1 AA 2021-11-26 18:49:00 living room 30 25
2 BB 2021-11-26 18:49:00 bathroom 32 23.5
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/412446.html
標籤:
上一篇:用一列擴展資料框,僅使用正數
