View Single Post
Old 02-19-2021, 08:20 AM   #338
chaley
Grand Sorcerer
chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.
 
Posts: 12,499
Karma: 8065348
Join Date: Jan 2010
Location: Notts, England
Device: Kobo Libra 2
Average Rating example

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:
Click image for larger version

Name:	Clipboard01.jpg
Views:	1584
Size:	50.4 KB
ID:	185466

It starts by selecting all the books in the library:
Click image for larger version

Name:	Clipboard04.jpg
Views:	1591
Size:	70.4 KB
ID:	185465

It then runs a template to compute the average ratings, saving that value in a chain variable (global):
Click image for larger version

Name:	Clipboard02.jpg
Views:	1618
Size:	21.6 KB
ID:	185467

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:
Click image for larger version

Name:	Clipboard05.jpg
Views:	1591
Size:	26.8 KB
ID:	185469

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:
Click image for larger version

Name:	Clipboard03.jpg
Views:	1613
Size:	71.0 KB
ID:	185468
chaley is offline   Reply With Quote