我正在尝试获取与某种特定颜色关联的观察总数。
Date <- c("2017-01-01","2017-01-01","2017-01-02","2017-01-03","2017-01-03","2017-01-03","2017-01-03","2017-01-04","2017-01-04","2017-01-05")
Factor<-c("red", "blue", "green", "red", "red", "green", "green", "blue", "blue", "green")
每个因素的不同表。他们每年的每一天都应该有一行,并包含观察的总数。
green <- table(cut(ex$Date[which(ex$Factor=="green")], 'day'))
它以某种方式起作用,但并不完美。如果没有对01.01.2017的观察,而对02.01.2017的观察,则它将以02.01.2017开头。数据集为一年。相同的问题会在年底出现(例如,2017年12月31日,2017年12月30日,...被省略)。
2017-01-02 1
2017-01-03 2
2017-01-04 0
2017-01-05 1
有人知道我该如何解决吗?
答案 0 :(得分:1)
这是一个使用aggregate
的基本R选项:
df <- data.frame(Date, Color, stringsAsFactors=FALSE)
aggregate(df$Color, by=list(Date=df$Date), FUN=function(x) { sum(x=="green") })
Date x
1 2017-01-01 0
2 2017-01-02 1
3 2017-01-03 2
4 2017-01-04 0
5 2017-01-05 1
数据:
Date <- c("2017-01-01","2017-01-01","2017-01-02","2017-01-03","2017-01-03","2017-01-03",
"2017-01-03","2017-01-04","2017-01-04","2017-01-05")
Color <- c("red", "blue", "green", "red", "red", "green", "green", "blue", "blue", "green")