2016-02-22 25 views
1

我有一個像子集r中使用最後一個值

x <- c(FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, TRUE, FALSE, TRUE) 

的數據集,我希望所有與最終價值的子集爲真,例如:

FALSE FALSE FALSE TRUE 
FALSE FALSE TRUE 
FALSE FALSE FALSE TRUE 
FALSE TRUE 

我已經使用循環試了又試獲得5以上的價值TRUE但由於不對稱,我沒有得到期望的結果。我已經複製了這個例子,其中原件有一些差異。任何解決方案將不勝感激。

+0

向我們展示你的'for'循環 – MaxPD

+1

也'trimws(strsplit(粘貼(X,崩潰=」「), 「(?<= TRUE)」,PERL假設'x < - as.logical(x)' - 'split(x,sum(x) - rev()= T)[[1]])' –

+0

can you explain using example ?, thankyou –

回答

3

你可以達到你想要使用只有兩行代碼是什麼:

splitAt <- function(x, pos) unname(split(x, cumsum(seq_along(x) %in% pos))) 

> splitAt(x, which(x)+1) 
[[1]] 
[1] "FALSE" "FALSE" "FALSE" "TRUE" 

[[2]] 
[1] "FALSE" "FALSE" "TRUE" 

[[3]] 
[1] "FALSE" "FALSE" "FALSE" "TRUE" 

[[4]] 
[1] "FALSE" "TRUE" 

數據:

x <- c("FALSE", "FALSE", "FALSE", "TRUE", 
     "FALSE", "FALSE", "TRUE", 
     "FALSE", "FALSE", "FALSE", "TRUE", 
     "FALSE", "TRUE") 

我給信貸this great SO answer其中認爲非常有用的功能splitAt()的我以上使用。

+1

cumsum(rev(x))))' – thelatemail

+0

我可以將它保存到數據框中 –

+0

你想要什麼結構?您在OP中指定的輸出似乎不適合數據框。數據框可以很容易地轉換爲列表(它是一個列表),但反之亦然。 –

1

這可以以一個簡單的在一個lapply

lapply(diff(c(0, which(x))), function(x) c(rep(FALSE, (x-1)), TRUE)) 

#[[1]] 
#[1] FALSE FALSE FALSE TRUE 

#[[2]] 
#[1] FALSE FALSE TRUE 

#[[3]] 
#[1] FALSE FALSE FALSE TRUE 

#[[4]] 
#[1] FALSE TRUE 

說明

  • which(x)給我們的TRUE值(4, 7, 11, 13
  • 從0開始的位置來完成,我們希望每個TRUE(其實質上是FALSE的計數) - diff(c(0, which(x))) - 4 3 4 2
  • 對於每一個我們需要一個載體,其是length(x)這些價值觀,與x - 1FALSE值,並1TRUE - c(rep(FALSE, (x-1)), TRUE)
  • lapply這是否爲每個4 3 4 2值,並返回一個列表

標杆

比較方案

library(microbenchmark) 

splitAt <- function(x, pos) unname(split(x, cumsum(seq_along(x) %in% pos))) 

microbenchmark(

    splitAt(x, which(x)+1), 

    {r <- rle(x)$lengths 
    lapply(r[seq(1,length(r), by=2)] , function(x) c(rep(FALSE, x), TRUE))}, 

    split(x, sum(x) - rev(cumsum(rev(x)))), 

    trimws(strsplit(paste(x, collapse=" "), "(?<=TRUE)", perl=T)[[1]]), 

    lapply(diff(c(0, which(x))), function(x) c(rep(FALSE, (x-1)), TRUE)) 

) 


    # min  lq  mean median  uq  max neval 
    # 83.827 86.3910 91.76449 88.9155 92.8350 155.722 100 
    # 94.373 97.6275 105.10872 101.1455 105.8545 307.927 100 
    # 85.532 88.0660 93.59524 91.7935 95.3715 126.419 100 
    #145.233 147.8755 152.65975 150.3250 156.5910 177.807 100 
    # 26.451 29.6130 31.81785 31.0470 33.1895 43.267 100 

數據

x <- c(F, F, F, T, F , F, T, F, F, F, T, F, T) 
+0

謝謝解決方案 –