首页 > 解决方案 > R读取excel,直到达到某个标准

问题描述

我有一个凌乱的 excel 文件,我需要按原样读入,但我想读入该文件,直到它到达“照常项目”的行

该值将始终位于第一列,并且该列中的任何其他字符串都不会匹配它。我也不希望它下面的任何信息出现在其他列中,因为它使我的数字列被读取为字符串(参见下面的分数示例)。

例如,我们可以假设这是 excel 文件:

library(tidyverse)

messy_excel <- tibble(id = c("1", "2", NA, NA, "Projects as usual", NA),
name = c("Joe", "Justin", NA, NA, NA, "Other info I don't want"),
score = c("50", "20", NA, NA, NA, "This shouldn't show"))

这就是我想要的:

library(tidyverse)
beautiful_excel <- tibble(id = c("1", "2"),
name = c("Joe", "Justin"),
score = c(50, 20))
~~~~~

Thank you!

标签: rexcelstringreadxl

解决方案


编辑:

根据@G5W 的建议,我过滤了值的位置,从这个答案中获得灵感:如何在 R 代码中查找值的行号

具体来说,我为每一行分配了一个行号,检测了目标字符串的位置,并删除了该行及其下方的行。然后我使用 hablar 包中的 retype() 函数来修复列类型。

library(tidyverse)
library(hablar)

messy_excel <- tibble(id = c("1", "2", NA, NA, "Projects as usual", NA),
name = c("Joe", "Justin", NA, NA, NA, "Other info I don't want"),
score = c("50", "20", NA, NA, NA, "This shouldn't show"))

#Give each line a row number
messy_excel$row_num <- seq.int(nrow(messy_excel))

#Identify the row where the garbage starts
messy_row <- which(grepl("Projects as usual", messy_excel$id))

#remove all rows below the garbage, remove the row_num column, correct column types, and remove the rows of all nas
clean_excel <- messy_excel %>%
  filter(row_num < messy_row) %>%
  dplyr::select(-row_num) %>%
  retype() %>%
  na.omit()

glimpse(clean_excel)

推荐阅读