如何在R資料框中查詢每行的零的頻率?
在資料分析中,我們需要非常謹慎地對待重複值,因為它們可能是故意輸入以在資料中製造偏差,這個值也可能是零。當我們有缺失資料並且資料收集者用零替換缺失值時,就會發生這種情況,這是一個錯誤的做法。為了找到R資料框中每行的零的頻率,我們可以使用rowSums函式來計算零值的個數,語法如下:
rowSums(“data_frame_name”==0)
考慮以下資料框:
示例
set.seed(189) x1<-sample(0:1,20,replace=TRUE) x2<-sample(0:5,20,replace=TRUE) x3<-sample(0:2,20,replace=TRUE) x4<-sample(0:1,20,replace=TRUE) x5<-sample(0:5,20,replace=TRUE) x6<-sample(0:10,20,replace=TRUE) df1<-data.frame(x1,x2,x3,x4,x5,x6) df1
輸出
x1 x2 x3 x4 x5 x6 1 1 5 2 1 3 1 2 1 3 0 0 5 2 3 1 2 2 1 2 5 4 1 4 0 0 0 7 5 0 0 2 0 5 0 6 0 5 1 1 2 5 7 0 5 1 1 1 6 8 0 4 1 0 3 1 9 0 4 1 1 3 4 10 0 1 2 0 4 5 11 1 1 2 0 4 0 12 1 2 0 0 5 1 13 1 3 0 0 1 5 14 1 0 0 0 5 1 15 0 3 0 1 5 10 16 0 3 2 1 3 2 17 1 3 0 1 1 7 18 0 3 1 1 2 9 19 1 3 2 0 3 5 20 1 4 0 1 2 1
計算每行零的個數:
示例
df1$Zeros<-rowSums(df1==0) df1
輸出
x1 x2 x3 x4 x5 x6 Zeros 1 0 1 1 0 4 3 2 2 0 4 2 1 4 10 1 3 0 3 2 0 0 3 3 4 0 5 0 0 4 4 3 5 1 1 1 0 3 6 1 6 1 2 1 1 4 5 0 7 1 0 2 0 0 4 3 8 1 0 0 1 3 2 2 9 0 2 0 0 5 1 3 10 0 4 1 1 4 2 1 11 0 3 0 0 1 3 3 12 0 0 0 0 1 5 4 13 1 2 0 1 5 8 1 14 1 1 2 1 1 10 0 15 1 3 0 1 4 6 1 16 1 5 2 0 0 8 2 17 0 1 2 0 0 4 3 18 0 5 2 1 3 1 1 19 1 2 2 0 0 2 2 20 1 3 2 1 3 4 0
讓我們來看另一個例子:
示例
y1<-sample(0:2,20,replace=TRUE) y2<-sample(0:1,20,replace=TRUE) y3<-sample(0:5,20,replace=TRUE) y4<-sample(0:4,20,replace=TRUE) y5<-sample(0:1,20,replace=TRUE) y6<-sample(0:5,20,replace=TRUE) y7<-sample(0:10,20,replace=TRUE) df2<-data.frame(y1,y2,y3,y4,y5,y6) df2
輸出
y1 y2 y3 y4 y5 y6 1 2 1 1 1 0 1 2 0 1 3 1 0 3 3 0 1 5 0 1 1 4 2 1 5 2 1 4 5 0 0 5 0 0 0 6 0 0 1 0 1 4 7 1 0 0 4 1 2 8 0 1 3 1 0 1 9 1 0 4 2 0 1 10 0 0 2 3 0 5 11 2 1 3 2 0 5 12 1 1 5 4 0 2 13 2 0 2 1 0 2 14 2 0 2 4 1 0 15 0 1 3 3 0 1 16 0 1 4 0 1 0 17 1 0 5 2 1 4 18 1 1 3 1 1 0 19 1 1 4 4 1 2 20 2 0 1 1 0 3
計算每行零的個數:
示例
df2$No_of_Zeros <-rowSums(df2==0) df2
輸出
y1 y2 y3 y4 y5 y6 No_of_Zeros 1 1 0 2 0 1 5 2 2 1 1 0 3 1 2 1 3 1 1 3 4 1 5 0 4 0 1 0 1 0 0 4 5 1 0 2 1 1 2 1 6 1 1 0 4 1 0 2 7 2 1 0 2 0 3 2 8 1 1 3 2 0 1 1 9 2 0 2 0 0 4 3 10 2 1 1 2 0 5 1 11 0 0 1 4 1 3 2 12 2 1 4 3 0 1 1 13 1 1 3 3 0 1 1 14 1 0 3 2 0 0 3 15 0 1 1 0 0 2 3 16 1 0 5 0 1 5 2 17 0 1 0 3 1 5 2 18 2 1 0 3 1 0 2 19 2 0 0 0 0 5 4 20 1 1 5 4 1 4 0
廣告