1

Suppose I have a dataframe with three columns.

a <- c(1,2,3,4)
b <- c(2,4,6,8)
c <- c(3,6,9,12)
df <- cbind(a,b,c)
df

This gives you...

     a b  c
[1,] 1 2  3
[2,] 2 4  6
[3,] 3 6  9
[4,] 4 8 12

Now suppose I want to create a new dataframe that takes the value TRUE if the value is greater than the column mean and FALSE if it's less than the column mean.

If I use the following command it uses the mean for the whole dataframe.

large <- df > mean(df)
large

So I get...

         a     b     c
[1,] FALSE FALSE FALSE
[2,] FALSE FALSE  TRUE
[3,] FALSE  TRUE  TRUE
[4,] FALSE  TRUE  TRUE

I would like to get

         a     b     c
[1,] FALSE FALSE FALSE
[2,] FALSE FALSE FALSE
[3,] TRUE  TRUE  TRUE
[4,] TRUE  TRUE  TRUE

2 Answers 2

4

This method will work for both data.frames and matrices (your example df is actually a matrix, not a data.frame)

sweep(df, 2, colMeans(df), '>')
#          a     b     c
# [1,] FALSE FALSE FALSE
# [2,] FALSE FALSE FALSE
# [3,]  TRUE  TRUE  TRUE
# [4,]  TRUE  TRUE  TRUE

Or, as suggested by @markus (same output and also works for both matrices and data.frames)

scale(df, scale = FALSE) > 0

If it is actually a data.frame, I believe using Map as below is faster than the methods above. However, if it is a matrix then using Map will not work at all.

as.data.frame(Map('>', df, colMeans(df)))
1
  • 1
    Don't know if this is any better but you might add this option to your post: scale(df, scale = FALSE) > 0
    – markus
    Nov 12, 2019 at 21:46
2

mean gets a single value for the whole matrix, we need colMeans

df > colMeans(df)[col(df)]

Or transpose the dataset, do the comparison and transpose

t(t(df) > colMeans(df))
2
  • 1
    Thanks. Now what if it was a different statistic, like the standard deviation?
    – Pasha S
    Nov 12, 2019 at 21:43
  • @PashaS. You can use df > apply(df, 2, sd)[col(df)]. or a vectorized option with library(matrixStats) df > colSds(df)[col(df)]
    – akrun
    Nov 12, 2019 at 21:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.