r - 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!
解决方案
编辑:
根据@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)
推荐阅读
- android - android:layout_weight 在 Xamarin 中不起作用
- javascript - 如何从函数设置事件处理程序
- r - 如何包含所有多项式和交互项
- python - 如何仅将字符串列表的一部分转换为整数
- c# - 将 SQL 查询更改为 LINQ、asp.net MVC
- java - 每次给出 Generate JavaDoc 命令时,javadoc 是否会扫描所有类?
- vb.net - 我在 vb.net 中遇到来自 Web 请求的响应字符串不可读的问题
- python - 在多个路由中将变量添加到烧瓶会话
- reactjs - Nextjs 你可能忘记从它定义的文件中导出你的组件,或者你可能混淆了默认和命名导入
- python - 如何在我的 python-2.7 代码中使用 `format` 的地方自动插入 `u`(unicode 指示符)到 `format` 函数调用?