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

用向量选择/子集空白行和非空白行[重复]

  •  1
  • LLL  · 技术社区  · 8 年前

    我想使用一个包含空白(“”)和非空白字符串的向量来对行进行子集,这样我得到的结果就像 dfgoal .

    dplyr::select() ,但我收到一条错误消息( Error: Strings must match column names. Unknown columns: tooth, , head, foot ).

    谢谢你的帮助!

    # Data
    df <- data.frame(avar=c("tooth","","","head","","foot","",""),bvar=c(1:8))
    
    # Vector 
    veca <- c("tooth","foot") 
    vecb <- c("") 
    vecc <- as.vector(rbind(veca,vecb)) 
    vecc <- unique(vecc) 
    
    # Attempt 
    library(dplyr)
    df <- df %>% dplyr::select(vecc)
    
    # Goal 
    dfgoal <- data.frame(avar=c("tooth","","","foot","",""),bvar=c(1,2,3,6,7,8)) 
    
    1 回复  |  直到 8 年前
        1
  •  0
  •   Maurits Evers    8 年前

    我不太清楚你想干什么。我想你是在问如何选择行 avar %in% veca 包括后续空白( "" )排。

    也许像这样用 tidyr::fill

    library(tidyverse)
    veca <- c("tooth","foot")
    df %>%
        mutate(tmp = ifelse(avar == "", NA, as.character(avar))) %>%
        fill(tmp) %>%
        filter(tmp %in% veca) %>%
        select(-tmp)
    #  avar bvar
    #1 tooth    1
    #2          2
    #3          3
    #4  foot    6
    #5          7
    #6          8