微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在 r 中,您将如何编码以根据两个分箱值的组合获取值?

如何解决在 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 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?