我有一个数据框,其中包含一个整数类型的日期列。
df
date values
11/25/18 a
11/30/18 b
12/4/18 a
12/5/18 b
12/5/18 a
12/6/18 b
12/6/18 c
12/6/18 a
12/6/18 a
12/7/18 b
12/7/18 c
12/7/18 a
12/9/18 b
12/12/18 a
12/12/18 c
12/13/18 b
1/9/19 a
1/9/19 c
1/9/19 b
1/10/19 d
1/10/19 d
1/10/19 d
1/10/19 a
1/11/19 c
1/11/19 d
2/1/19 a
2/10/19 a
2/13/19 b
3/14/19 d
3/17/19 c
5/4/19 d
5/5/19 c
5/6/19 d
5/31/19 a
我尝试使用此代码,但无法在一个月内进行汇总
df %>% group_by(DATE) %>%
count(values)
从这开始,我得到了每天的频率
group_by(month = month(date)) %>% count(values)
当我尝试使用此代码汇总月份中的日期时,出现以下错误
(Error in as.POSIXlt.character(as.character(x), ...) :
character string is not in a standard unambiguous format)
我想要这样的输出
date values freq
11/18 a 1
11/18 b 1
12/18 a 6
12/18 b 5
12/18 c 6
,其他月份相同。
答案 0 :(得分:2)
从date
提取月份,然后使用count
library(dplyr)
df %>%
mutate(month = format(as.Date(date, "%m/%d/%y"), "%m/%y")) %>%
count(month, values)
# month values n
# <chr> <fct> <int>
# 1 01/19 a 2
# 2 01/19 b 1
# 3 01/19 c 2
# 4 01/19 d 4
# 5 02/19 a 2
# 6 02/19 b 1
# 7 03/19 c 1
# 8 03/19 d 1
# 9 05/19 a 1
#10 05/19 c 1
#11 05/19 d 2
#12 11/18 a 1
#13 11/18 b 1
#14 12/18 a 6
#15 12/18 b 5
#16 12/18 c 3
或者完全保留在基数R中,我们可以使用aggregate
aggregate(date~month+values,
transform(df, month = format(as.Date(date, "%m/%d/%y"), "%m/%y")), length)
答案 1 :(得分:1)
我们可以将base R
与table
一起使用
with(df1, as.data.frame(table(format(as.Date(date, "%m/%d/%y"), "%m/%y"), values)))
优点是它还将提供有关“ Freq”为0时不存在的组合的信息