0

I want to Calculate median pop density for every possible combination of temp and precipitation values. For example, the pop density for places that have:

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...

My data is situated like so:

 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 

So far I have only binned these data: using the following code:

# 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,7000,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,32,2),sep="")
# bucketing values into bins
group_tags1 <- cut(test$t , 
                  breaks=breaks1, 
                  include.lowest=TRUE, 
                  right=FALSE, 
                  labels=tags1)
# inspect bins
summary(group_tags1)

I have tried a couple of four loops, but could not get them to work. Any ideas?

1 Answers1

0

You can try :

breaks <- seq(0,7010,10)
tags <- paste0(seq(0,7000,10),"-",seq(10,7010,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,32,2))
test$group_tags1 <- cut(test$t ,breaks=breaks1, 
                        include.lowest=TRUE, 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
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213