sven_k - 26 days ago 7

R Question

Probably this is very straightforward but I can't come up with a quick solution.

I have a dataframe df:

`df <- data.frame(a = c(1,2,3,4,5), b = c(6,7,8,9,10))`

a b

1 1 6

2 2 7

3 3 8

4 4 9

5 5 10

And I would want to know how each value compares to the column mean, excluding the value being compared from the column mean.

So that:

- 1 is compared to (2+3+4+5)/4)
- 2 is compared to (1+3+4+5)/4)
- etc.

Giving:

df_colmeans_exVal:

a_2 and b_2 would be a result of a[i]/(columnMean of all values in the rest of the column)

colMean of all values in the rest of the column would be. 'colmeanrest' or cmr:

`c_a c_b`

1 3.5 8.5

2 3.25 8.25

3 3 8

4 2.75 7.75

5 2.5 7.5

and so a[i]/cmr[i] would give

`c_a c_b`

1 0.285 0.705

2 0,615 0,848

3 1 1

4 1,454 1.161

5 2 1.333

Many thanks for any help!

Answer Source

If I understand it correctly, the following should do it.

```
res <- sapply(df, function(x)
sapply(seq_along(x), function(i) x[i]/mean(x[-i]))
)
res <- as.data.frame(res)
names(res) <- paste("c", names(res), sep = "_")
res
# c_a c_b
#1 0.2857143 0.7058824
#2 0.6153846 0.8484848
#3 1.0000000 1.0000000
#4 1.4545455 1.1612903
#5 2.0000000 1.3333333
```