我有一個資料框,其中一串列示事件的開始 (1) 和結束 (2)。事件的持續時間是 1 到 2 之間的零數。這個事件可能會發生多次。該列如下所示:
event <- c(1002, 100000000000000000, 10002000102000, 10000, 100000210200000000, 10020000010200000)
我試過stringr::str_count(string = event, pattern = "0"),但當然,這給了我零的總數。我需要的是第一個 1 和 2 之間的零數。應該洗掉 2 之后的零。
2
17
3 1
4
5 1
2 1
我不知道如何做到這一點,可能是我在這里的方法都是錯誤的。誰能給我一些方向?
uj5u.com熱心網友回復:
基本 R 選項 -
#To avoid scientific notation in numbers
options(scipen = 99)
sapply(strsplit(as.character(event), ''), function(x) {
#position of 1
one <- which(x == 1)
#position of 2
two <- which(x == 2)
#If event is still going on
if(length(two) == 0) {
#Calculate last position - position 1
two <- length(x)
return(two - one)
}
return(two - one - 1)
})
#[[1]]
#[1] 2
#[[2]]
#[1] 17
#[[3]]
#[1] 3 1
#[[4]]
#[1] 4
#[[5]]
#[1] 5 1
#[[6]]
#[1] 2 1
uj5u.com熱心網友回復:
一種tidyverse方法(預先將數字轉換為字符;函式的用途format是避免數字的科學格式):
library(tidyverse)
event <- format(c(1002, 100000000000000000, 10002000102000, 10000, 100000210200000000, 10020000010200000), scientific = F)
event %>%
str_extract_all("(?<=1)0 ") %>%
map(~ nchar(.x))
#> [[1]]
#> [1] 2
#>
#> [[2]]
#> [1] 17
#>
#> [[3]]
#> [1] 3 1
#>
#> [[4]]
#> [1] 4
#>
#> [[5]]
#> [1] 5 1
#>
#> [[6]]
#> [1] 2 1
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/341292.html
