我想计算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)
Run Code Online (Sandbox Code Playgroud)
想要在每列中看到零并表示为百分比
谢谢
Rol*_*and 10
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
Run Code Online (Sandbox Code Playgroud)
如果你必须,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
Run Code Online (Sandbox Code Playgroud)
这是使用lapply的另一种方法,尽管这种方法适用于数据帧。
lapply(data_a, function(x){ length(which(x==0))/length(x)})
Run Code Online (Sandbox Code Playgroud)