This example action computes the average rating for 3 Genres and their children then stores those ratings in a tags-like custom column in the form 'genre name':average_rating.
Here is the complete chain:
It starts by selecting all the books in the library:
It then runs a template to compute the average ratings, saving that value in a chain variable (global):
The template in the chain variables action is:
Code:
program:
genres = 'Comics, Mysteries, Science Fiction';
res = '';
for g in genres:
ratings = from_search('rating', strcat('#genre:"=.', g, '"'));
total = 0;
cnt = 0;
for r in ratings:
if r != "None" then
total = add(total, r);
cnt = add(cnt, 1)
fi
rof;
if cnt ># 0 then
avg = divide(divide(total, 2), cnt)
else
avg = 0
fi;
res = list_union(res, strcat(g, ':', avg), ',')
rof;
res
I chose to ignore unrated books. If no books are rated then the average is set to zero. One could just as easily put nothing into the result.
@capink:I couldn't get the mean() function to work. How do I convert the result of "from_search()" to an "iterable"?
Next it saves the computed value to a tags-like column:
The template in the Single Field Edit is
Code:
program:
globals(avg_ratings = '');
An example of the output is:
Code:
Comics:1.5, Mysteries:2.0, Science Fiction:3.0
Finally it clears the selection: