haimen
haimen

Reputation: 2015

replace all column values except one with mean values in all rows in R

Suppose I have dataframe as follows,

> test <- data.frame(a=6:15, b=14:23, c= rep(1:5,2))
> test
    a  b c
1   6 14 1
2   7 15 2
3   8 16 3
4   9 17 4
5  10 18 5
6  11 19 1
7  12 20 2
8  13 21 3
9  14 22 4
10 15 23 5

I want to make the data frame as follows,

     a    b c
1 10.5 18.5 1
2 10.5 18.5 2
3 10.5 18.5 3
4 10.5 18.5 4
5 10.5 18.5 5

where the values are ,

> mean(test$a)
[1] 10.5
> mean(test$b)
[1] 18.5
> unique(test$c)
[1] 1 2 3 4 5

Can anybody help me in converting the dataframe as required? My try is,

data.frame(a=rep(mean(test$a),5), b=rep(mean(test$b),5), c=unique(test$c))

But when I have more number of variables, it becomes difficult to use this way and it is not efficient also. Is there a easy and better way to do this?

Upvotes: 1

Views: 335

Answers (1)

nicola
nicola

Reputation: 24520

You can try:

data.frame(c(list(c=unique(test$c)),lapply(test[-3],mean)))
#  c    a    b
#1 1 10.5 18.5
#2 2 10.5 18.5
#3 3 10.5 18.5
#4 4 10.5 18.5
#5 5 10.5 18.5 

Upvotes: 5

Related Questions