生成一列时间

generating a column of times

在我的数据集中,我想包含一个仅包含 times 的列。我生成了一列从 2018 年到 2020 年的随机日期,但时间戳似乎并没有像我希望的那样在一天中随机生成。

我就是这样制作 date/time 列的。

data$date <- sample(seq(as.POSIXct('2018/01/01'), as.POSIXct('2020/12/31'), by = "day"),
                    length(data$date), replace = TRUE)

我用它来获取时间

data$time <- format(data$date, format = "%H:%M:%S")

但这就是它的样子

> dput(data[1:10,-c(5,6)])
structure(list(order_num = c(501073L, 969942L, 1091101L, 590143L, 
390404L, 219429L, 1025827L, 689629L, 694348L, 435848L), date = structure(c(1542344400, 
1552194000, 1550379600, 1534568400, 1523336400, 1563426000, 1595826000, 
1552712400, 1534309200, 1547960400), class = c("POSIXct", "POSIXt"
), tzone = ""), total_sale = c(36.3853391310075, 35.9405038506853, 
55.6254974332793, 47.7214780063544, 61.4086594373677, 32.8631076291332, 
33.3640439679803, 40.8944394660076, 54.9455495252506, 48.12597580998
), season = c("Spring", "Winter", "Winter", "Fall", "Fall", "Spring", 
"Summer", "Summer", "Fall", "Fall"), time = c("00:00:00", "00:00:00", 
"00:00:00", "01:00:00", "01:00:00", "01:00:00", "01:00:00", "01:00:00", 
"01:00:00", "00:00:00")), row.names = c(NA, 10L), class = "data.frame")

我希望全天有更多的随机时间,例如9:33:35、14:56:43,等等。

我认为这个功能可以帮助您像您提到的那样在一天中生成随机时间

randomtimes <- function(N, st="2018/01/01", et="2020/12/31") {
  st <- as.POSIXct(as.Date(st))
  et <- as.POSIXct(as.Date(et))
  dt <- as.numeric(difftime(et,st,unit="sec"))
  ev <- sort(runif(N, 0, dt))
  rt <- st + ev
}

然后你就可以将它应用到你的数据中了。这里 nrow 只是计算数据中的行数,然后使用该值生成日期数。您也可以将 nrow(data) 换成 10,因为那是数据中的行数

data$date <- randomtimes(nrow(data))

您可以使用 -

生成随机时间
data$time <- format(as.POSIXct(sample(86400, nrow(data)), origin = '1970-01-01'), '%T')

这会生成从 1 到 86400(一天中的秒数)的随机数,将其更改为 POSIXct 类型并使用 format.

仅从中提取时间