【问题标题】:Cannot remove rows from data.frame [duplicate]无法从 data.frame 中删除行 [重复]
【发布时间】:2021-01-27 07:44:42
【问题描述】:

我有一系列的 excel 文件,并且很长时间以来我一直在使用这个基本代码来导入我的数据。我没有对数据或代码进行任何更改,但我不再正确读取数据。我阅读的文件如下:

apply_fun <- function(filename) {
  data <- readxl::read_excel(filename, sheet = "Section Cut Forces - Design", 
                       skip = 1, col_names = TRUE) 
  data <- data[-1,] 
  data <- subset(data, StepType == "Max")
  data <- data[,c(1,2,6,10)]
  data$id <- filename
  return(data)
}

filenames <- list.files(pattern = "\\.xlsx", full.names = TRUE)

first <- lapply(filenames,apply_fun)
out <- do.call(rbind,first)

out 的前几行看起来像:

structure(list(SectionCut = c("1", "1", "1", "1", "1", "2", "2", 
"2", "2", "2"), OutputCase = c("Service (after losses)", "LL-1", 
"LL-2", "LL-3", "LL-4", "Service (after losses)", "LL-1", "LL-2", 
"LL-3", "LL-4"), V2 = c("11.522", "28.587", "42.246000000000002", 
"44.212000000000003", "36.183", "9.8469999999999995", "23.989000000000001", 
"37.408999999999999", "43.401000000000003", "40.450000000000003"
), M3 = c("299728.66100000002", "42863.517999999996", "63147.332999999999", 
"69628.464000000007", "59196.74", "0", "27.942", "44.863999999999997", 
"46.31", "36.204999999999998"), id = c("./100-12-S00.xlsx", "./100-12-S00.xlsx", 
"./100-12-S00.xlsx", "./100-12-S00.xlsx", "./100-12-S00.xlsx", 
"./100-12-S00.xlsx", "./100-12-S00.xlsx", "./100-12-S00.xlsx", 
"./100-12-S00.xlsx", "./100-12-S00.xlsx")), row.names = c(NA, 
-10L), class = c("tbl_df", "tbl", "data.frame"))

我尝试将行删除为:

out2 <- out[!grep("Service (after losses)", out$OutputCase),]

但结果是 0 次观察。

我必须说,这对我来说刚刚开始成为一个问题。我已经能够成功运行这段代码几个月了,从来没有遇到过问题。

【问题讨论】:

    标签: r excel dataframe


    【解决方案1】:

    () 是正则表达式中的特殊符号。当您在grep/grepl 等函数中使用它们时,它们具有特殊含义。您可以在grep 中使用fixed = TRUE 来精确匹配它们。此外,! 应与 grepl 一起使用,- 应与 grep 一起使用以删除行。

    out[-grep("Service (after losses)", out$OutputCase, fixed = TRUE),]
    

    除此之外,这看起来像是完全匹配,那么为什么要使用grep 的模式匹配呢?试试看:

    out[out$OutputCase != 'Service (after losses)', ]
    

    【讨论】:

      猜你喜欢
      • 2021-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-13
      • 1970-01-01
      • 1970-01-01
      • 2019-11-02
      • 2018-10-23
      相关资源
      最近更新 更多