我目前正在使用一个大型物候数据集,其中有多个树木的观察在给定的一个月。我想把这些观测结果划分为三个月的星团或垃圾箱。我目前正在使用以下代码:
Cluster.GN <- ifelse(Master.feed.parts.gn$yr.mo=="2007.1", 1,
ifelse(Master.feed.parts.gn$yr.mo=="2007.11", 1,....
ifelse(Master.feed.parts.gn$yr.mo=="2014.05", 17, NA)这段代码可以工作,但由于有超过50个月的时间,所以非常麻烦。我很难找到另一种解决办法,因为这种“绑定”不是基于观察的数量(因为每个月可能有多达4000次观测),也不是按时间顺序排列的,因为有些月已经错过了。如能提供任何帮助,将不胜感激。
更新I:我在R中使用了“剪切”函数,我尝试将中断设置为17,因为这是我应该拥有的三个月的桶数。但是当我使用table(Cluster.GN)时,它显示只有奇数编号的“回收箱”有观察结果(对不起,我不知道如何将表上传到这里)。>Cluster.GN <- Master.feed.parts.gn$yr.mo,breaks= 17,c("1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17"),include.lowest=TRUE)
发布于 2015-11-09 02:43:01
更新:这个答案是一个快速的黑客,我没有检查zoo库。要获得正确的方法,请参见zoo::as.yearqtr()
您所需要做的就是将yr.mo字段从一年月字符串(例如2007.11)转换为范围为1..17的整数,每季度(即月份1..3转换为第一个bin,4..6变为第二个bin等等)。(我不知道8年(2007..2014) *4个季度=32个垃圾箱如何减少到只有17个垃圾箱,除非你的数据很稀少。但无论如何.)
不需要麻烦如果其他梯子。
为了获得更高的性能,请使用stringi库,stri_split_fixed()
sample_wr <- function(...) sample(..., replace=T)
# Generate sample data (you're supposed to provide this to code, to make your issue reproducible)
set.seed(123)
N <- 20
df <- data.frame(yr.mo =
paste(sample_wr(2007:2014, N), sample_wr(1:12, N), sep='.') )
# [1] "2009.11" "2013.9" "2010.8" "2014.12" "2014.8" "2007.9" "2011.7"
# [8] "2014.8" "2011.4" "2010.2" "2014.12" "2010.11" "2012.9" "2011.10"
#[15] "2007.1" "2014.6" "2008.10" "2007.3" "2009.4" "2014.3"
yearmonth_to_integer <- function(xx) {
yy_mm <- as.integer(unlist(strsplit(xx, '.', fixed=T)))
return( (yy_mm[1] - 2006) + (yy_mm[2] %/% 3) )
}
Cluster.GN <- sapply(x, yearmonth_to_integer)
# 2009.11 2013.9 2010.8 2014.12 2014.8 2007.9 2011.7
# 6 10 6 12 10 4 7
# 2014.8 2011.4 2010.2 2014.12 2010.11 2012.9 2011.10
# 10 6 4 12 7 9 8
# 2007.1 2014.6 2008.10 2007.3 2009.4 2014.3
# 1 10 5 2 4 9 为了获得更高的性能,请使用dplyr或data.table库:
require(dplyr)
# something like the following, currently doesn't work,
# you have to handle two intermediate columns from yy_mm
# You get to fix this :)
df %>% mutate(yy_mm = as.integer(unlist(strsplit(yr.mo, '.', fixed=T))),
quarter = yy_mm[1]-2006 + yy_mm[2] %/% 3 )https://stackoverflow.com/questions/33597728
复制相似问题