簡體   English   中英

識別由 NA 分隔的組

[英]Identify groups separated by NA

我想將分組列添加到我的數據中。 我的數據是文本列,並且有 NA 分隔組。 這是示例,組是我想要實現的結果。 我不知道每組將包含多少行,但總是有 NA 分隔組(最后一組除外)。 那么如何創建組列呢?

library(tidyverse)

data <- tibble(raw = c("This", "Is", "First", NA, "This", "Is", "Second", NA, "And", "Third"),
               group = c(1,1,1,1,2,2,2,2,3,3))

一種選擇是根據NA值創建一個邏輯向量並使用cumsum

library(dplyr)
data %>% 
      mutate(groupNew = cumsum(lag(is.na(raw), default = TRUE)) )
# A tibble: 10 x 3
#   raw    group groupNew
#   <chr>  <dbl>    <int>
# 1 This       1        1
# 2 Is         1        1
# 3 First      1        1
# 4 <NA>       1        1
# 5 This       2        2
# 6 Is         2        2
# 7 Second     2        2
# 8 <NA>       2        2
# 9 And        3        3
#10 Third      3        3

如果當前值不是 NA,則取 NA 的累積和並加一。

data %>% mutate(group = cumsum(is.na(raw)) + !is.na(raw))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM