How to solve R Markdown (Knit) “'closure' is not subsettable”?

删除回忆录丶 提交于 2019-12-08 03:06:17

问题


I am trying to use RMarkdown (Knit) for the first time to produce pdf. The default file (File > New File > R Markdown) works well, it shows the generated pdf when compiled. For example, the following code runs,

```{r cars}
summary(cars)
```

However, if I just change cars with "myData," it does not compile and shows,

Error in object[[i]] : object of type 'closure' is not subsettable
Calls: <Anonymous> ... withVisible -> eval -> eval -> summary -> summary.default
Execution halted

I have "myData" loaded in the global-environment and can do other operations in original R script. Can someone please provide some guideline. Thank you very much for your time.


回答1:


Running an Rmarkdown file starts a new R session.

Within the new session, you can load the data.frames that are stored in the data package, but other datasets must be loaded from within the Rmarkdown document.

To get myData to show up in your Rmarkdown document,

  1. save the file somewhere with save in your current R session
  2. then in your Rmarkdown document, use load to open up the data set

So, in your current R session:

save(myData, file="<path>/myData.Rdata")

and in your Rmarkdown file:

```{r myDataSummary}
load("<path>/myData.Rdata")
summary(myData)
```

If your data is stored as a text file, and you don't wish to store a separate .R file, use read.csv or friend directly within your Rmarkdown file.

```{r myDataSummary}
myData <- read.csv("<path>/myCSV.csv")
summary(myData)
```



回答2:


This is the error you get when you try to subset (= via x[i]) a function. Since this error is caused by summary(cars) in your code, we may surmise that the cars object refers to a function in the scope in which the document is knit.

You probably forgot to load your data, or you have a function with the same name defined in the current scope.




回答3:


As @Imo explained, the basic problem is the new session. So, the answer would be adding the script in the rMarkdown. However, it will create few more hiccups. Here is how I handled few of them,

```{r global_options, include=FALSE}
source(file = "C:\\Path\\to\\my\\file.R")
knitr::opts_chunk$set(fig.width=12, fig.height=8, fig.path='Figs/',
                      echo=FALSE, warning=FALSE, message=FALSE)
```


来源:https://stackoverflow.com/questions/37943824/how-to-solve-r-markdown-knit-closure-is-not-subsettable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!