2014-07-24 46 views
0

我想從數據幀my.data中提取第一個非零元素爲1的每一行。提取第一個非零元素爲1的行

my.data <- read.table(text = ' 

    x1 x2 x3 x4 
     0 0 1 1 
     0 0 0 1 
     0 2 1 1 
     2 1 2 1 
     1 1 1 2 
     0 0 0 0 
     0 1 0 0 
', header = TRUE) 

my.data 

desired.result <- read.table(text = ' 

    x1 x2 x3 x4 
     0 0 1 1 
     0 0 0 1 
     1 1 1 2 
     0 1 0 0 
', header = TRUE) 

desired.result 

我甚至不知道從哪裏開始。對不起,如果這是重複的。感謝您的任何建議或意見。

回答

3

這裏有一個辦法:

# index of rows 
idx <- apply(my.data, 1, function(x) any(x) && x[as.logical(x)][1] == 1) 

# extract rows 
desired.result <- my.data[idx, ] 

結果:

x1 x2 x3 x4 
1 0 0 1 1 
2 0 0 0 1 
5 1 1 1 2 
7 0 1 0 0 
+0

得主,根據微基準最快的解決方案 – Vlo

1
  1. 使用apply遍歷所有行:

    first.element.is.one <- apply(my.data, 1, function(x) x[x != 0][1] == 1) 
    

    傳遞給apply功能的x第一[1]非零[x != 0]元件進行比較,以== 1。它將被調用一次每行,x將在您的示例中爲四個向量。

  2. 使用which提取候選行的索引(和刪除NA值,太):

    desired.rows <- which(first.element.is.one) 
    
  3. 選擇矩陣的行 - 你可能知道如何做到這一點。

獎金的問題:在哪裏可以在步驟2中提到的NA值從何而來?

1

可能不是最好的答案,但:

rows.to.extract <- apply(my.data, 1, function(x) { 
    no.zeroes <- x[x!=0] # removing 0 
    to.return <- no.zeroes[1] == 1  # finding if first number is 0 

    # if a row is all 0, then to.return will be NA 
    # this fixes that problem 
    to.return[is.na(to.return)] <- FALSE # if row is all 0 

    to.return 
}) 
my.data[rows.to.extract, ] 

    x1 x2 x3 x4 
1 0 0 1 1 
2 0 0 0 1 
5 1 1 1 2 
7 0 1 0 0 
相關問題