To find the percent of zeros in each row of an R data frame, we can follow the below steps −
First of all, create a data frame.
Then, use rowSums function along with ncol function to find the percent of zeros in each row of the data frame.
Let’s create a data frame as shown below −
x<-sample(0:2,25,replace=TRUE) y<-sample(0:2,25,replace=TRUE) z<-sample(0:2,25,replace=TRUE) a<-sample(0:2,25,replace=TRUE) df<-data.frame(x,y,z,a) df
On executing, the above script generates the below output(this output will vary on your system due to randomization) −
x y z a 1 0 0 2 2 2 2 1 2 0 3 0 1 0 2 4 1 1 2 1 5 0 1 2 1 6 1 1 1 0 7 2 0 0 0 8 2 2 0 0 9 0 1 2 1 10 2 1 0 2 11 2 0 0 1 12 0 0 1 0 13 1 0 0 2 14 2 0 0 2 15 1 2 2 1 16 0 0 0 1 17 2 2 2 2 18 2 0 0 0 19 1 1 0 2 20 2 1 0 2 21 0 1 1 2 22 0 2 1 0 23 1 1 0 2 24 2 0 0 0 25 2 1 1 0
Find the percent of zeros in each row
Using rowSums function along with ncol function to find the percent of zeros in each row of the data frame df −
x<-sample(0:2,25,replace=TRUE) y<-sample(0:2,25,replace=TRUE) z<-sample(0:2,25,replace=TRUE) a<-sample(0:2,25,replace=TRUE) df<-data.frame(x,y,z,a) df$Percent_0s<-(rowSums(df==0)/ncol(df))*100 df
x y z a Percent_0s 1 1 0 2 1 25 2 1 0 1 0 50 3 2 2 1 1 0 4 0 1 0 0 75 5 2 0 1 1 25 6 2 2 0 2 25 7 0 1 1 0 50 8 2 1 0 0 50 9 2 0 2 1 25 10 1 2 2 1 0 11 1 2 2 2 0 12 0 2 2 0 50 13 0 1 1 0 50 14 0 1 2 2 25 15 1 0 1 1 25 16 1 0 0 1 50 17 2 2 2 1 0 18 1 1 1 2 0 19 0 0 0 1 75 20 2 1 0 2 25 21 2 1 2 1 0 22 1 0 0 2 50 23 2 0 2 1 25 24 0 0 1 1 50 25 1 2 2 1 0