I have the following dataframe(df1). This dataframe contains a row called "Mean" that has the mean of each column.
GDP per_capita
France 2 5
Spain 4 10
Italy 6 15
Mean 4 10
I want to create a function that duplicates the columns of df1, and the value of each of these new columns is the subtraction of each cell minus its respective mean, divided by its mean. Like this:
GDP per_capita GDP_diff per_capita_diff
France 2 5 (2-4)/4 (5-10)/10
Spain 4 10 (4-4)/4 (10-10)/10
Italy 6 15 (6-4)/4 (15-10)/10
Mean 4 10 (4-4)/4 (10-10)/10
So at the end, it should look like this:
GDP per_capita GDP_diff per_capita_diff
France 2 5 -0.5 -0.5
Spain 4 10 0 0
Italy 6 15 0.5 0.5
Mean 4 10 0 0
I have to assume that every dataframe that will be using this function has a row called "Mean". So far this is what I have:
new.function <- function(df){
name.df= colnames(df)
new.df = apply(df, FUN = function(x) (x-Mean)/Mean, MARGIN = 2)
colnames(new.df) = paste(name.df,"diff",sep ="_")
result = cbind(df,new.df)
return(result)
}
However the outputs I'm getting are all wrong. It is not substracting nor dividing like I want it to.