【问题标题】:Remove Rows occurring after a String R Data frame删除字符串 R 数据帧之后发生的行
【发布时间】:2021-11-06 07:43:39
【问题描述】:

我想在数据框列中出现某个字符串后删除所有行。我只想返回出现在 A 列中“总计”上方的 3 行。将排除出现在“总计”下方的 2 行。

A            B       
Bob Smith    01005
Carl Jones   01008
Syndey Lewis 01185
total
Adam Price   01555
Megan Watson 02548

【问题讨论】:

  • @NadPat 链接的问题是关于删除包含特定字符串的行。 OP 希望删除不完全相同的特定字符串下方(包括)的每一行。

标签: r dplyr data-manipulation


【解决方案1】:

这有点笨拙,但这应该可以解决您想要它做的事情:

library(dplyr)

df <- data.frame(A = c("Bob Smith", "Carl Jones", "Sydney Lewis", "total", "Adam Price", "Megan Watson"),
                 B = c("01005", "01008", "01185", NA, "01555", "02548"))

index <- df[df$A=="total",] %>% rownames()
df %>% slice(1:index)

【讨论】:

  • 我认为这行不通。没有行名。
  • 你可以稍微重新排列你的代码:df %&gt;% slice_head(n = which(.$A == "total") - 1).
  • 谢谢@MartinGal。它适用于大多数是默认数据类型的数据帧。现在我添加了指定这适用于数据帧的代码,此代码有效。
【解决方案2】:

我们可以使用row_numberwhich进行子集化

library(dplyr)

df %>% filter(row_number() < which(A=='total'))

             A     B
1    Bob Smith 01005
2   Carl Jones 01008
3 Syndey Lewis 01185

【讨论】:

  • 不过,答案很好。
【解决方案3】:
A <- c('Bob Smith','Carl Jones','Syndey Lewis','total','Adam Price','Megan Watson')

B <- c('01005','01008','01185','','01555','02548')

df <- data.frame(A, B) 

val =  which(df$A=="total")  #get index of total

C = df[1:val-1,]

【讨论】:

    【解决方案4】:

    你可以使用

    library(dplyr)
    
    df %>% 
      filter(cumsum(A == "total") == 0)
    

    返回

    # A tibble: 3 x 2
      A            B    
      <chr>        <chr>
    1 Bob Smith    01005
    2 Carl Jones   01008
    3 Syndey Lewis 01185
    

    数据

    structure(list(A = c("Bob Smith", "Carl Jones", "Syndey Lewis", 
    "total", "Adam Price", "Megan Watson"), B = c("01005", "01008", 
    "01185", NA, "01555", "02548")), problems = structure(list(row = 4L, 
        col = NA_character_, expected = "2 columns", actual = "1 columns", 
        file = "literal data"), row.names = c(NA, -1L), class = c("tbl_df", 
    "tbl", "data.frame")), class = c("spec_tbl_df", "tbl_df", "tbl", 
    "data.frame"), row.names = c(NA, -6L), spec = structure(list(
        cols = list(A = structure(list(), class = c("collector_character", 
        "collector")), B = structure(list(), class = c("collector_character", 
        "collector"))), default = structure(list(), class = c("collector_guess", 
        "collector")), skip = 1L), class = "col_spec"))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-08
      • 2022-01-07
      • 1970-01-01
      相关资源
      最近更新 更多