我有一个RMarkdown脚本,如果我手动运行块,无论是一次运行一个,还是使用"全部运行";。但当我尝试使用knitr
生成HTML或PDF时,我会遇到一个错误:Error in select(responses, starts_with("Q1 ") & !contains("None")) %>% : could not find function "%>%"
实际整行显示:
cols <- select(responses, starts_with("Q1 ") & !contains("None") ) %>% colnames()
我正在处理一项调查的数据,其中有很多问题是";选择尽可能多的"应用";键入问题,并有一个开放式的";以上";选项在这一点上,我正是抽出我想要的列(所有Q1响应,但不是Q10或Q11响应,也不是开放式响应(,这样我就可以使用pivot_longer()
并总结响应。它在脚本中工作得很好:我得到了一个我想要的确切列名的列表,然后计算值。
但当我尝试使用knitr()
时,它在%>%
上会出现问题。
processing file: 02_Survey2020_report.Rmd
|.... | 6%
ordinary text without R code
|......... | 12%
label: setup (with options)
List of 1
$ include: logi FALSE
|............. | 19%
ordinary text without R code
|.................. | 25%
label: demographics gender
Quitting from lines 28-46 (02_Survey2020_report.Rmd)
Error in select(responses, starts_with("Q1 ") & !contains("None")) %>% :
could not find function "%>%"
Calls: <Anonymous> ... handle -> withCallingHandlers -> withVisible -> eval -> eval
Execution halted
一个简化的可重复的例子得到了相同的结果。我运行以下程序,得到了我所期望的,一个整洁的表格,上面有每个答案的选择次数:
example <- data.frame("id" = c(009,008,007,006,005,004,003,002,001,010), "Q3_Red" = c("","","","Red","","","","Red","Red","Red"), "Q3_Blue" = c("","","","","","Blue","Blue","Blue","",""),
"Q3_Green" = c("","Green","Green","","","","","Green","",""), "Q3_Purple" = c("","Purple","","","Purple","","Purple","","Purple","Purple"),
"Q3_None of the above" = c(009,008,"Verbose explanation that I don't want to count." ,006,005,004,003,002,"Another verbose entry.",010)
)
cols <- select(example, starts_with("Q3") & !contains("None") ) %>% colnames()
example %>%
pivot_longer(cols = all_of(cols),
values_to = "response") %>%
filter(response != "") %>%
count(response)
但是,当我使用ctrlshift<kbd&k>
processing file: 00a_reproducible_examples.Rmd
Quitting from lines 9-25 (00a_reproducible_examples.Rmd)
Error in select(example, starts_with("Q3") & !contains("None")) %>% colnames() :
could not find function "%>%"
Calls: <Anonymous> ... handle -> withCallingHandlers -> withVisible -> eval -> eval
Execution halted
编织者为什么对烟斗犹豫不决?
最近我遇到了类似的问题。不确定是否有更复杂的解决方案,但在每个代码块中加载库对我来说都很有效。若要显示代码的结果,在没有关于库加载的消息的情况下,添加消息=FALSE。
示例:
```{r, echo=FALSE, message = FALSE}
library(dplyr)
>>your code with dplyr<<
```