user2807119 - 1 year ago 68

R Question

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

Answer Source

```
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
```