2013-09-23 116 views
2

我想計算R數據幀中每列中的零的數量並將其表示爲百分比。這個百分比應該添加到原始數據框的最後一行? 例如在R中的數據幀的列中計數零,並以百分比表示

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) 

希望看到每列中的零和表達爲百分比

感謝

回答

6
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 

如果你一定要,rbind到基體(通常不是一個真正的好主意)。

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 
2

prop.table組合和一些*apply工作可以給你同樣的答案@羅蘭的

> prop <- apply(data_a, 2, function(x) prop.table(table(x))*100) 
> rbind(data_a, sapply(prop, "[", 1)) 
     x y z 
[1,] 0 3 3 
[2,] 4 0 6 
[3,] 6 9 9 
[4,] 0 12 0 
[5,] 10 15 15 
[6,] 40 20 20 
3

下面是使用lapply多了一個方法,這將用於數據幀的工作,雖然。

lapply(data_a, function(x){ length(which(x==0))/length(x)})