微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

读excel直到达到一定标准

如何解决读excel直到达到一定标准

我有一个凌乱的excel文件,我需要按原样读取,但是我想读取该文件,直到找到“像往常一样的项目”行为止。

此值将始终在第一列中,并且该列中的任何其他字符串都不会匹配它。我也不希望其他列下面的任何信息,因为它使我的数字列作为字符串读入(请参见下面带有score的示例)。

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

library(tidyverse)

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

这就是我想要的:

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

Thank you!

解决方法

编辑:

根据@ G5W的建议,我过滤出了值的位置,并从以下答案中得到了启发:How to find row number of a value in R code

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

library(tidyverse)
library(hablar)

messy_excel <- tibble(id = c("1","2",NA,"Projects as usual",NA),name = c("Joe","Justin","Other info I don't want"),score = c("50","20","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)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。