mql4beginner
mql4beginner

Reputation: 2233

How to subtract the mean of each variable from the mean of a specific variable

I would like to subtract the mean of each variable from the mean of a variable named 'birds' and create a new data frame that will contain the results.In my real data frame I have hundreds of variables so I would like to do it automatically.Any Idea how to do so? I tried with this line of code without the mean function and it works (on the same data frame) :

setNames(as.data.frame(cbind(g, mean(dat$birds)-mean(dat))), c(names(dat), paste0(names(dat),'_new')))

but I don't understand how to use mean as part of the code,I tried:

setNames(as.data.frame(cbind(g, mean(dat$birds)-mean(dat))), c(names(dat), paste0(names(dat),'_new')))

Here is my toy data frame.

dat <- read.table(text = " birds    wolfs     snakes
                    3        9         7
                    3        8         4
                    1        2         8
                    1        2         3
                    1        8         3
                    6        1         2
                    6        7         1
                    6        1         5
                    5        9         7
                    3        8         7
                    4        2         7
                    1        2         3
                    7        6         3
                    6        1         1
                    6        3         9
                    6        1         1   ",header = TRUE)

Upvotes: 0

Views: 2003

Answers (1)

Maksim Gayduk
Maksim Gayduk

Reputation: 1082

I hope I understood your question correctly. This should create a new object, in this case - just a vector, where mean of "birds" column is substracted from the means of other columns. This should also work for any size of the data frame.

mean=mean(dat$birds)
dat2=colMeans(dat[2:dim(dat)[2]])-mean

In the future, please provide reproducible example (in your code, object 'g' is not defined) and an example of the expected output, so that it would be clear what you are trying to achieve.

Upvotes: 3

Related Questions