我在编写的脚本中遇到错误,只有在我dplyr运行时才会发生.当我找到一个dplyr我想要使用的函数时,我第一次遇到它,之后我安装并运行了包.以下是我的错误示例:
首先,我从excel中读取一个表,其中包含我将用作索引的列值:
library(readxl)
examplelist <- read_excel("example.xlsx")
Run Code Online (Sandbox Code Playgroud)
该文件的内容是:
1 2 3 4
1 1 4 1
2 3 2 1
4 4 1 4
Run Code Online (Sandbox Code Playgroud)
然后我构建了一个数据框:
testdf = data.frame(1:12, 13:24, 25:36, 37:48)
Run Code Online (Sandbox Code Playgroud)
然后我有一个循环调用一个使用examplelistas作为索引值的函数.
testfun <- function(df, a, b, c, d){
value1 <- df[[a]]
value2 <- df[[b]]
value3 <- df[[c]]
value4 <- df[[d]]
}
for (i in 1:nrow(examplelist)){
testfun(testdf, examplelist[i, 1], examplelist[i, 2],
examplelist[i, 3], examplelist[i, 4])
}
Run Code Online (Sandbox Code Playgroud)
当我没有运行这个脚本时dplyr,一切都很好,但是dplyr它给了我错误:
Error in .subset2(x, i, exact = exact) : invalid subscript type 'list'
Run Code Online (Sandbox Code Playgroud)
为什么会dplyr导致此错误,我该如何解决?
我认为 MKR 的答案是一个有效的解决方案,我将通过一些替代方案详细说明原因。
该readxl库是 的一部分,并使用该函数tidyverse返回一个 tibble( ) 。这是一种特殊类型的数据帧,与基本行为有所不同,特别是打印和子集化(请阅读此处)。tbl_dfread_excel
Tibbles 还清楚地描述了
[和[[:[总是返回另一个 tibble,[[总是返回一个向量。不再drop = FALSE
所以你现在可以看到你examplelist[i, n]将返回一个 tibble 而不是长度为 1 的向量,这就是 usingas.numeric有效的原因。
library(readxl)
examplelist <- read_excel("example.xlsx")
class(examplelist[1, 1])
# [1] "tbl_df" "tbl" "data.frame"
class(examplelist[[1, 1]])
# [1] "numeric"
class(as.numeric(examplelist[1, 1]))
# [1] "numeric"
class(as.data.frame(examplelist)[1, 1])
# [1] "numeric"
Run Code Online (Sandbox Code Playgroud)
我的工作流程倾向于使用,tidyverse因此您可以使用[[子集或者as.data.frame如果您不需要小标题。