df <- data.frame(Tag = c(1, 1, 1, 1, 2, 2, 2, 2),
x = c(9,7,3,2,1,1,1,1),
y = c(1,2,3,4,1,2,3,4))
cor_fun<- function(x,y){
val <- cor(x,y)
return(val)}
df %>%
group_by(Tag) %>%
summarise(c = cor_fun(x,y))
Here we are trying to compute correlation between x
& y
by group_by
(Tag).the problem is when we compute correlation for x & y and , any one of the columns has standard deviation 0 it spits error of
the standard deviation is zero
which is not acceptable in production. so what I except is whenever the standard deviation is zero
occurs the function should return mean of x else correlation output should be returned.i have tried reproducing the same scenario which is pasted below please guide me on this.
using try-catch in Function name cor_fun
.
Brief Requirement
- Inside Function, we can use try-catch function and look for
the standard deviation is zero
this error, - If
the standard deviation is zero
this error occurs Function shall return mean of x. - If an error is not found then return
cor(x,y)
output.
Expected is no error message instead function should return mean of x value.