gpt4 book ai didi

r - Group_by,并创建具有持续时间的新列

转载 作者:行者123 更新时间:2023-12-01 11:11:20 26 4
gpt4 key购买 nike

我有数据集,df,

  Subject      Folder      Message    Date
A Out 9/9/2019 5:46:38 PM
A Out 9/9/2019 5:46:40 PM
A Out 9/9/2019 5:46:42 PM
B Out 9/9/2019 5:48:00 PM
B Out 9/9/2019 5:48:01 PM
C Out 9/10/2019 5:49:01 PM

如何按主题对其进行分组,然后找到持续时间,同时创建一个新的持续时间列。这是我想要的输出:

  Subject   Duration    Group
A 4 sec outdata1
B 1 sec outdata2
C 0 sec outdata3

这是我的输出:

         structure(list(Subject = structure(c(1L, 1L, 1L, 2L, 2L, 3L), .Label =                 c("A", 
"B", "C"), class = "factor"), Folder = structure(c(1L, 1L, 1L,
1L, 1L, 1L), .Label = "Out", class = "factor"), Message = c("",
"", "", "", "", ""), Date = structure(c(2L, 3L, 4L, 5L, 6L, 1L
), .Label = c("9/10/2019 5:49:01 PM", "9/9/2019 5:46:38 PM",
"9/9/2019 5:46:40 PM", "9/9/2019 5:46:42 PM", "9/9/2019 5:48:00 PM",
"9/9/2019 5:48:01 PM"), class = "factor")), row.names = c(NA,
-6L), class = "data.frame")

这是我尝试过的:

df %>%  
mutate(Date = mdy_hms(Date)) %>%
transmute(Subject, Duration = diff = difftime(as.POSIXct(Date, format =
"%m/%d/%Y %I:%M:%S %p"),as.POSIXct(Date,
format = "%m/%d/%Y %I:%M:%S %p" ), units = "secs")) %>%
ungroup %>%
distinct %>%
mutate(grp = str_c("Outdata", row_number()))

感谢任何帮助

最佳答案

在这里,我们可以在summarise 步骤之前使用'Subject' 分组

library(dplyr)
library(lubridate)
library(stringr)
df %>%
mutate(Date = mdy_hms(Date)) %>%
group_by(Subject) %>%
summarise(Duration = diff(range(Date))) %>%
mutate(grp = str_c("Outdata", row_number()))
# A tibble: 3 x 3
# Subject Duration grp
# <fct> <drtn> <chr>
#1 A 4 secs Outdata1
#2 B 1 secs Outdata2
#3 C 0 secs Outdata3

如果我们需要控制unit使用difftime

df %>%
mutate(Date = mdy_hms(Date)) %>%
group_by(Subject) %>%
summarise(Duration = difftime(max(Date), min(Date), unit = 'sec')) %>%
mutate(grp = str_c("Outdata", row_number()))

关于r - Group_by,并创建具有持续时间的新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59997158/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com