我有一个数据框架如下:
v2 v3
10:37:38 adakjl
10:38:02 sdjfisaofj
11:11:57 asdhad
12:42:02 asjla我想提取另一个数据帧,它合并时间值在同一小时内的行,并计数这样的条目数:
v2 v3
10:00:00-11:00:00 2
11:00:00-12:00:00 1
12:00:00-13:00:00 1
....我想知道怎么做?我搜索了动物园的文件,但在同一年或每季度才找到了合并数据的方法。
提前谢谢。
发布于 2016-01-21 16:31:51
你可以
df <- read.table(header=T, text="v2 v3
10:37:38 adakjl
10:38:02 sdjfisaofj
11:11:57 asdhad
12:42:02 asjla")
tab <- as.data.frame(table(strptime(df$v2, "%H:%M:%S")$hour), stringsAsFactors = F)
tab[, 1] <- sprintf("%02d:00:00-%02d:00:00", as.integer(tab[, 1]), as.integer(tab[, 1])+1)
tab
# Var1 Freq
# 1 10:00:00-11:00:00 2
# 2 11:00:00-12:00:00 1
# 3 12:00:00-13:00:00 1发布于 2016-01-21 16:36:16
使用dplyr非常简单。
## sample data
dat <- data.frame(time = c("10:37:38", "10:38:02", "11:11:57", "12:42:02"),
value = c("adakjl", "sdjfisaofj", "asdhad", "asjla"))
## count hourly observations
library(dplyr)
dat %>%
mutate(time = substr(time, 1, 2)) %>%
count(time) %>%
mutate(time = as.integer(time),
time = paste0(time, ":00:00-", time+1, ":00:00"))这是同意的输出。
Source: local data frame [3 x 2]
time n
(chr) (int)
1 10:00:00-11:00:00 2
2 11:00:00-12:00:00 1
3 12:00:00-13:00:00 1发布于 2016-01-23 12:02:38
这个解决方案使用动物园包。
1)创建一个函数,给定时间的toInveral产生相应的时间间隔。然后让动物园在使用该函数转换v2和使用aggregate = length执行计数时读取它。如果您希望将fortify.zoo语句保留为动物园对象,则省略它。
library(zoo)
toInterval <- function(x) {
hr <- as.POSIXct(x, format = "%H:%M:%S")
h00 <- "%H:00:00"
paste(format(hr, h00), format(hr + 3600, h00), sep = "-")
}
z <- read.zoo(DF, header = TRUE, FUN = toInterval, aggregate = length)
fortify.zoo(z)
giving:
Index z
1 10:00:00-11:00:00 2
2 11:00:00-12:00:00 1
3 12:00:00-13:00:00 12)这里的是一个更好的变体,如果您以后想要操作它的话。它像这样使用chron中的"times"类(或者省略+ 1/24来使用开始时间而不是结束时间):
library(chron)
toHour <- function(x) trunc(times(x), "hour") + 1/24
z2 <- read.zoo(DF, header = TRUE, FUN = toHour, aggregate = length)
fortify.zoo(z2)给予:
Index z2
1 11:00:00 2
2 12:00:00 1
3 13:00:00 1注意:我们使用这个data.frame作为输入:
Lines <- "v2 v3
10:37:38 adakjl
10:38:02 sdjfisaofj
11:11:57 asdhad
12:42:02 asjla"
DF <- read.table(text = Lines, header = TRUE)https://stackoverflow.com/questions/34929006
复制相似问题