I have a data table where I want to calculate the geometric mean for each row over several columns. Some of the values will have zeros so I need these to be excluded.
The geometric mean from Wiki is: "The geometric mean is defined as the nth root of the product of n numbers" so for 2 numbers its simply the square root of their product.
The nth root in my case will vary on each row depending on how many of the values are non-zeros in them.
In my example below the top 2 rows of the results column was worked out as follows:
1: (a * c)^(1/2)
2: (a * b * c)^(1/3)
so I need the formula to look at columns a:c, take the product of the non-zero values and then take the nth root of how many non-zero values there were.
library(data.table)
dt <- data.table(a = c(0.5, 0.3,0,0.6), b = c(0,0.4,0.1,0),
c = c(0.9,0.5,0.1,0), Result = c(0.67, 0.39, 0.1, 0.6))