【发布时间】:2019-11-21 16:44:10
【问题描述】:
我们会收到一份 Excel 格式的月度报告,我只需要特定的值。以前,我可以使用 readxl grep 行号所需的列,然后从那里开始:
library(readxl)
file <- read_excel(readxl_example("deaths.xlsx"), col_names = FALSE))
row_pos <- grep(pattern = "actor", file$..2)
然后我可以为我想要的特定列添加更多内容:
col_pos <- grep(pattern = "Has Kids", file)
这用于返回我想要的行位置,我可以提取并继续处理我的数据。
我在这里故意使用 now 不正确的$..2 语法。最近的更新将此约定更改为$...2
我的问题是如何为第一个 grep 实现更强大的选择,以便在实现 readxl(或任何其他包)中的微小语法更改时不必更新所有代码?
我试过了:
row_pos <- grep(pattern = "actor", x = file %>% select(contains("2")))
但这只会返回第一个值。
这是有关数据发生了什么的一些上下文的其余管道。
values <- as.data.frame(t(file[row_pos, col_pos]), stringsAsFactors = FALSE, row.names = NULL)
等等。 谢谢!
【问题讨论】:
-
函数
names(file)可用于检索列名。然后像file[[grep("2", names(file))]]这样的东西会选择正确的列。