Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

counting zeros in columns in data frame in R and express as percentage

Tags:

r

I want to count number of zeros in each column in a R data frame and express it as a percentage. This percentage should be added to last row of the original data frame? example

x <- c(0, 4, 6, 0, 10)
y <- c(3, 0, 9, 12, 15)
z <- c(3, 6, 9, 0, 15)

data_a <- cbind(x,y,z)

want to see the zeros in each column and express as percentage

Thanks

like image 883
user2807119 Avatar asked Nov 30 '22 12:11

user2807119


2 Answers

x <- c(0, 4, 6, 0, 10)
y <- c(3, 0, 9, 12, 15)
z <- c(3, 6, 9, 0, 15)

data_a <- cbind(x,y,z)
#This is a matrix not a data.frame.    

res <- colSums(data_a==0)/nrow(data_a)*100

If you must, rbind to the matrix (usually not really a good idea).

rbind(data_a, res)
#      x  y  z
#      0  3  3
#      4  0  6
#      6  9  9
#      0 12  0
#     10 15 15
# res 40 20 20
like image 136
Roland Avatar answered Dec 15 '22 12:12

Roland


Here is one more method using lapply, this would work for a data frame though.

lapply(data_a, function(x){ length(which(x==0))/length(x)})
like image 24
Chirayu Chamoli Avatar answered Dec 15 '22 11:12

Chirayu Chamoli