apply function TRUE/FALSE Ratios

Viewed 719

I have a dataframe with only TRUE/FALSE values

 tf <- as.data.frame(matrix(c(rep(TRUE,5),rep(FALSE,5)),10,10))

and I want to calculate the percentage of TRUE values for each column. Thus I wrote the following apply function, which however only returns an empty vector:

overlay <- apply(tf,2,function(x) sum(x == TRUE)/nrow(x))

What am I doing wrong?

3 Answers

This should be fast

colMeans(tf)
# V1  V2  V3  V4  V5  V6  V7  V8  V9 V10 
#0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5

I don't know why you used nrow but Check this:

overlay <- apply(tf,2,function(x) sum(x == TRUE)/length(x) * 100)

The x inside your anonymous functions function(x) sum(x == TRUE)/nrow(x) is a vector corresponding to a certain row. Hence, it's not nrow what you need but length:

apply(tf, 2, function(x) sum(x == TRUE) / length(x))

On the other hand, you may achieve the same in a vectorized manner with

colMeans(tf)
#  V1  V2  V3  V4  V5  V6  V7  V8  V9 V10 
# 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 
Related