First off, I'm new to both R and Stack Overflow, so I apologize in advance for the inevitable faux pas or silly mistakes I make in this question and will do what I can to remedy them. In the meantime, please excuse my naïveté.
I'm using the R package Bchron
to calibrate radiocarbon dates (i.e., turning 14C ages with error into probability distributions from a calibration curve, and especially, resulting in a point estimate (e.g., a mean) for that probability distribution). My goal is to get a vector of the weighted average ages resulting from calibrating multiple dates simultaneously. In this case, the weighted average is the sum of the products of the calibration age grid and the probability densities.
Let's say we are calibrating just three dates as follows:
library(Bchron)
ages1 <- BchronCalibrate(ages=c(3445,11553,7456),
ageSds=c(50,230,110),
calCurves=c('intcal13','intcal13','shcal13'),
ids=c('sample1','sample2','sample3'))
Bchron
outputs calibrations (i.e., from BchronCalibrate()
) as a list of vectors. It's easy enough to get the mean one at a time:
print (sum(ages1$'sample1'$ageGrid * ages1$'sample1'$densities))
But when we calibrate multiple dates we get a list of dates (designated by "ids" above), each comprised of the calibration list for that date. Given the nested lists, I'm having a very hard time figuring out how to get multiple means in a vector from my list(s). Snooping around Stack Exchange, I've found lots of examples for iterating over a list, or even doing nested apply functions, but unfortunately, given my relative inexperience, I can't quite seem to adapt them to my problem. The following is what I've got so far.
Given that the ageGrid
and densities
vectors are always the 4th and 5th list items for each date in the parent list, I think it should be simple... something like
for(sample.age in ages1) {
sapply(ages1[[sample.age]],sum([4]*[5]))
}
Given all the errors I've gotten in my various attempts, though, it's clear my syntax or (more probably) my entire line of thinking on this is mixed up.
And even if I can get the basic for loop to work, how do I ask it to return a vector?
I appreciate any help on this subject, and will especially appreciate answers that are simple enough for a novice like me to understand.
Cheers, Matt