如何解决在 r 中,您将如何编码以根据两个分箱值的组合获取值?
我想计算温度和降水值的每种可能组合的中值流行密度。例如,以下地点的人口密度:
Mean annual temp of 4 to 6 C and 500 to 510 mm precip
Mean annual temp of 4 to 6 C and 510 to 520 mm precip
Mean annual temp of 4 to 6 C and 520 to 530 mm precip
Mean annual temp of 6 to 8 C and 500 to 510 mm precip
Mean annual temp of 6 to 8 C and 510 to 520 mm precip
Mean annual temp of 6 to 8 C and 520 to 530 mm precip and so on...
我的数据是这样的:
Pp Pmm t
21.18 83.81 31.24
14.81 174.49 30.80
14.81 129.59 30.72
52.04 230.53 30.59
8.56 206.69 30.57
5.06 194.85 30.55
到目前为止,我只对这些数据进行了分箱:使用以下代码:
# MAKING precipitation BINS
# set up cut-off values
breaks <- seq(0,7010,10)
# specify interval/bin labels
tags <- paste(seq(0,7000,10),"-",seq(10,sep="")
# bucketing values into bins
group_tags <- cut(test$Pmm,breaks=breaks,include.lowest=TRUE,right=TRUE,labels=tags)
# inspect bins
summary(group_tags)
# Temperature Bins
# set up cut-off values
breaks1<- seq(0,32,2)
# specify interval/bin labels
tags1 <- paste(seq(0,30,2),seq(2,sep="")
# bucketing values into bins
group_tags1 <- cut(test$t,breaks=breaks1,right=FALSE,labels=tags1)
# inspect bins
summary(group_tags1)
我尝试了四个循环,但无法使它们工作。有什么想法吗?
解决方法
你可以试试:
breaks <- seq(0,7010,10)
tags <- paste0(seq(0,7000,10),"-",seq(10,10))
test$group_tags <- cut(test$Pmm,breaks=breaks,include.lowest=TRUE,right=TRUE,labels=tags)
breaks1<- seq(0,32,2)
tags1 <- paste0(seq(0,30,2),seq(2,2))
test$group_tags1 <- cut(test$t,breaks=breaks1,right=FALSE,labels=tags1)
#Create all possible combination of group_tags and group_tags1
all_combns <- expand.grid(group1 = test$group_tags,group2 = test$group_tags1)
#For each combination calculate average value of `Pp`.
do.call(rbind,Map(function(x,y) data.frame(Pmm_group = x,temp_group = y,average = mean(test$Pp[test$group_tags == x & test$group_tags1 == y])),all_combns$group1,all_combns$group2)) -> result
result
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。