代码之家  ›  专栏  ›  技术社区  ›  falecomdino

基于列中的字符和数据帧中的出现顺序为每个组创建子集行

  •  1
  • falecomdino  · 技术社区  · 7 年前

    B <- data.frame(State = c(rep("Arizona", 8), rep("California", 8), rep("Texas", 8)), 
      Account = rep(c("Balance", "Balance", "In the Bimester", "In the Bimester", "Expenses",  
      "Expenses", "In the Bimester", "In the Bimester"), 3), Value = runif(24))
    

    Account 元素出现4次 "In the Bimester" , 每个状态有两个元素, "Expenses"

    这里的顺序很重要,因为第一个块与第二个块指的不是同一个东西。

    账户 方法每个元素的元素数 账户 元素(因子本身)可以更改。例如,在某些状态下 “在双酯中” 可以有6行和第二行,7行;但是,我不能用这个第四个变量来区分。

    渴望的: 我想对我的数据进行子集,将它们分开 按每个状态,仅按每个状态或第二个“块”将第一个“块”的行子集。

    我有一个解决方案,使用 data.table

    library(data.table)
    B <- as.data.table(B)
    B <- B[, .(Account, Value, index = 1:.N), by = .(State)]
    x <- B[Account == "Expenses", .(min_ind = min(index)), by = .(State)]
    B <- merge(B, x, by = "State")
    B <- B[index < min_ind & Account == "In the Bimester", .(Value), by = .(State)]
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   M--    7 年前

    您可以使用 dplyr 包裹:

    library(dplyr)
    B %>% mutate(helper = data.table::rleid(Account)) %>% 
          filter(Account == "In the Bimester") %>% 
          group_by(State) %>% filter(helper == min(helper)) %>% select(-helper)
    
    # # A tibble: 6 x 3
    # # Groups:   State [3]
    #        State         Account      Value
    #       <fctr>          <fctr>      <dbl>
    # 1    Arizona In the Bimester 0.17730148
    # 2    Arizona In the Bimester 0.05695585
    # 3 California In the Bimester 0.29089678
    # 4 California In the Bimester 0.86952723
    # 5      Texas In the Bimester 0.54076144
    # 6      Texas In the Bimester 0.59168138
    

    如果而不是 min 您使用 max "In the Bimester" 对于每个 State . 您也可以排除 Account select(-helper,-Account)

    附笔 如果你不想使用 rleid data.table 只需使用 dplyr thread .