2016-03-22 79 views
0

我有一個數據幀,其中一些列包含非常少的值大於0,我想刪除這些列。從R中的數據幀刪除列基於值的數量> 0

例如,如果我想在下面的data.frame中刪除所有小於5的值大於0的列,我該如何去做?

Name,Col1,Col2,Col3,Col4,Col5,Col6 
Row1,0,0,0,0,10,400 
Row2,125.0,2.50,0,0,5,0 
Row3,10,0,0,10,100,70 
Row4,10,0,50,0,0,10 
Row5,489,0,30,0,35,50 
Row6,0,0,450.5,0,10,400 
Row7,125.5,0,2.50,0,0,5 
Row8,10,0,0.50,10,100,70 
Row9,10,0,50,0,0,10 
Row10,489,0,0,0,35,50 

回答

4

你可以嘗試用colSums邏輯子集結合:

df1[, colSums(df1 > 0) >= 5] 
#  Col1 Col3 Col5 Col6 
#Row1 0.0 0.0 10 400 
#Row2 125.0 0.0 5 0 
#Row3 10.0 0.0 100 70 
#Row4 10.0 50.0 0 10 
#Row5 489.0 30.0 35 50 
#Row6 0.0 450.5 10 400 
#Row7 125.5 2.5 0 5 
#Row8 10.0 0.5 100 70 
#Row9 10.0 50.0 0 10 
#Row10 489.0 0.0 35 50 

數據

df1 <- structure(list(Col1 = c(0, 125, 10, 10, 489, 0, 125.5, 10, 10, 
     489), Col2 = c(0, 2.5, 0, 0, 0, 0, 0, 0, 0, 0), Col3 = c(0, 0, 
     0, 50, 30, 450.5, 2.5, 0.5, 50, 0), Col4 = c(0L, 0L, 10L, 0L, 
     0L, 0L, 0L, 10L, 0L, 0L), Col5 = c(10L, 5L, 100L, 0L, 35L, 10L, 
     0L, 100L, 0L, 35L), Col6 = c(400L, 0L, 70L, 10L, 50L, 400L, 5L, 
     70L, 10L, 50L)), .Names = c("Col1", "Col2", "Col3", "Col4", "Col5", 
     "Col6"), class = "data.frame", row.names = c("Row1", "Row2", 
     "Row3", "Row4", "Row5", "Row6", "Row7", "Row8", "Row9", "Row10")) 
+1

今天學到了一些東西! – Wave

0

這應該可以幫助你想要做什麼。這將統計一列中的數字觀察值。

library(plyr) 

count(dataframe, names(dataframe)) 

使用其他人的答案是爲df1是。

count(df1, "Col1") 

    Col1 freq 
1 0.0 2 
2 10.0 4 
3 125.0 1 
4 125.5 1 
5 489.0 2 

要循環訪問列,請使用一些應用函數或循環來獲取所需內容。

從這裏開始,你只需要做一個「if」語句來檢查0的freq < = 5是否相應地刪除。

1

另一種選擇是Filter(來自@ RHertel的帖子使用數據)

Filter(function(x) sum(x>0)>=5, df1) 
#  Col1 Col3 Col5 Col6 
#Row1 0.0 0.0 10 400 
#Row2 125.0 0.0 5 0 
#Row3 10.0 0.0 100 70 
#Row4 10.0 50.0 0 10 
#Row5 489.0 30.0 35 50 
#Row6 0.0 450.5 10 400 
#Row7 125.5 2.5 0 5 
#Row8 10.0 0.5 100 70 
#Row9 10.0 50.0 0 10 
#Row10 489.0 0.0 35 50 
相關問題