【发布时间】:2017-08-22 19:18:00
【问题描述】:
我正在尝试在 R 中设置一个函数,以准备特定格式的数据以输入相关图。在处理数据集时,我倾向于使用 dplyr,因为它清晰且易于使用,但在使用 dplyr 时尝试将数据集和指定的列名传递给此函数时遇到了问题。
这是设置,为了清楚起见,包括在此处(略微缩写形式)。我没有遇到任何错误,在发布之前我确认 corrData 设置正确:
library(corrplot)
library(tidyverse)
library(stringr)
table2a <- table2 %>%
mutate(example_index = str_c(country,year, sep="."))
这是实际的功能:
prepCorr <- function(dtable, x2, index2) {
practice <- dtable %>%
select(index2, x2) %>%
mutate(count=1) %>%
complete(index2, x2)
practice$count[is.na(practice$count)] <- 0
practice <- spread(practice, key = x2, value = count)
M <- cor(practice)
return(M)
}
prepCorr(table2a, type, example_index)
每当我运行这个函数时,我都会得到:
Error in overscope_eval_next(overscope, expr) : object 'example_index' not found
我也尝试利用 quosures 来解决此问题,但这样做时会收到不同的错误。当我运行以下修改后的代码时:
prepCorr <- function(dtable, x2, index2) {
x2 <- enquo(x2)
index2 <- enquo(index2)
practice <- dtable %>%
select(!!index2, !!x2) %>%
mutate(count=1) %>%
complete(!!index2, !!x2)
practice$count[is.na(practice$count)] <- 0
practice <- spread(practice, key = !!x2, value = count)
return(cor(practice))
}
prepCorr(table2a, type, example_index)
我明白了:
Error in !index2 : invalid argument type
我在这里做错了什么,我该如何解决这个问题?我相信我正在使用 dplyr 0.7 进行澄清。
更新:用可重现的示例替换旧示例。
【问题讨论】:
-
你能发一个reproducible example吗?
-
如果我编辑问题以使用 tidyverse 包中的 table2 而不是此处显示的表格,可以吗?它应该很好地用于此目的。
-
当然,只要它给出相同的错误,我们可以用它来“调试”
-
好的,现在应该可以重现了,谢谢指点。
-
保存 RStudio 以解决 RStudio 特定的问题。 (RStudio 界面,或在 RGui 或 R 命令行中工作的代码,但不在 RStudio 中。)