[英]Find the run length of 1 in column number 1,3,5 and find count of continuous two 1 in column 2,4,6 data is in data frame of R
我有數據作為 R 中的數據框:
> qa
A_1 A_2 B_1 B_2 C_1 C_2
1 1 1 1 1 1 1
2 1 1 1 1 1 1
3 1 0 1 0 1 1
4 1 1 1 0 1 1
5 1 1 1 1 1 0
6 0 0 1 1 1 1
7 0 0 1 1 1 1
8 0 1 1 0 0 0
9 1 1 1 0 0 0
10 1 1 1 1 0 1
請建議實現以下結果的最佳方法。
> qc
A_1 A_2 B_1 B_2 C_1 C_2
1 5 2 10 2 7 2
在上面的數據框中:
A_1 = 5(在qa$A_1
最大運行次數),
A_2 = 2(參考A_1=5有兩個連續的1),
B_1 = 10(在qa$B_1
最大運行次數),
B_2 = 2(B_1=10有兩個連續的1),
C_1 = 7(在qa$C_1
最大運行次數),
C_2 = 2(C_1=7 有三個連續的 1)
輸入:
qa <- data.frame(A_1 = c(1,1,1,1,1,0,0,0,1,1),
A_2 = c(1,1,0,1,1,0,0,1,1,1),
B_1 = rep(1,10),
B_2 = c(1,1,0,0,1,1,1,0,0,1),
C_1 = c(rep(1,7),0,0,0),
C_2 = c(1,1,1,1,0,1,1,0,0,1))
rle
為您提供運行長度編碼,因此我們可以使用它來提取第一次連續運行。
基礎R
sapply(qa, function(x) with (rle(x), lengths[values == 1][1]))
輸出:
A_1 A_2 B_1 B_2 C_1 C_2
5 2 10 2 7 4
或者如果您更喜歡tidyverse
包:
library(tidyverse)
map_dfr(qa, ~rle(.)$lengths[rle(.)$values==1][1])
輸出:
# A tibble: 1 x 6
A_1 A_2 B_1 B_2 C_1 C_2
<int> <int> <int> <int> <int> <int>
1 5 2 10 2 7 4
或者如果你想要一個 data.frame 而不是 tibble 你可以轉換它:
>as.data.frame(map_dfr(qa, ~rle(.)$lengths[rle(.)$values==1][1]))
A_1 A_2 B_1 B_2 C_1 C_2
1 5 2 10 2 7 4
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.