我正在尝试创建一个闪亮的应用程序,允许您根据用户定义的子分析下载格式良好的PDF报告.我发现这个要点包含一个最小的例子,它运作得很好.但是,当我尝试添加一个基于Rstudio画廊的"每加仑英里数"示例的情节时,我在尝试调整代码时遇到了一些错误.
这是我的server.R
代码:
library(knitr)
library(datasets)
library(ggplot2)
mpgData <- mtcars
mpgData$am <- factor(mpgData$am, labels = c("Automatic", "Manual"))
shinyServer(function(input, output) {
formulaText <- reactive({
paste("mpg ~", input$variable)
})
# Return the formula text for printing as a caption
output$caption <- renderText({
formulaText()
})
# Generate a plot of the requested variable against mpg and only
# include outliers if requested
output$mpgPlot <- renderPlot({
boxplot(as.formula(formulaText()),
data = mpgData,
outline = input$outliers)
})
myPlot1 <- reactive({
p <- print(ggplot(mpgData, …
Run Code Online (Sandbox Code Playgroud) 我想添加整体摘要行,同时使用dplyr按组计算摘要.我发现了各种问题,询问如何做到这一点,例如这里,这里和这里,但没有明确的解决方案.一种可能的方法是执行count
两次并绑定行:
mtcars %>%
count(cyl, gear) %>%
bind_rows(
count(mtcars, gear)
)
Run Code Online (Sandbox Code Playgroud)
这几乎产生我需要的东西(最左边的列有NAs而不是'Total'或类似的):
cyl gear n
<dbl> <dbl> <int>
1 4 3 1
2 4 4 8
3 4 5 2
4 6 3 2
5 6 4 4
6 6 5 1
7 8 3 12
8 8 5 2
9 NA 3 15
10 NA 4 12
11 NA 5 5
Run Code Online (Sandbox Code Playgroud)
我错过了一个更简单/内置的解决方案吗?
我正在使用R创建流行曲线(每天疾病病例数的直方图),并且在格式化x轴方面有点挣扎.
我知道ggplot提供了非常好的图形和易于操作的轴(了解日期并在R中用ggplot2绘制直方图)但在这种情况下我更喜欢使用hist()
命令,因为我同时描述了2种不同的模式,如下面(我不认为你可以在ggplot中做类似的事情):
这里的问题是x轴不是从第一种情况开始,有太多的刻度线,我希望能够有一个系统的日期标记,例如.每7天,或每月1日.
数据存储在数据库(dat.geo)中,每个疑似病例一行,其中包括发病日期和郊区信息(直方图中是黑色还是白色),如下所示:
> head(dat.geo)
number age sex suburb Date_of_Onset
1 1 12 F x 2011-10-11
2 2 28 M x 2011-10-10
3 3 15 F x 2011-10-12
4 4 12 M y 2011-10-25
5 5 10 F x 2011-10-15
6 6 9 M y 2011-10-20
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
pdf(file='1.epi.curve.pdf')
hist(dat.geo$Date_of_Onset[(dat.geo$suburb=="x")], "days",
format = "%d %b %y", freq=T, col=rgb(0,0,0,1), axes=T, main="", add=T)
hist(dat.geo$Date_of_Onset[(dat.geo$suburb=="y")], "days",
format = "%d %b %y", freq=T, main="", col=rgb(1,1,1,.6), add=T, axes=F)
dev.off()
Run Code Online (Sandbox Code Playgroud)
我已经尝试过抑制轴并在以后使用此代码添加一个被操纵的轴
axis(1, …
Run Code Online (Sandbox Code Playgroud) 我正在参加Coursera实践机器学习课程,课程作业需要使用此数据集构建预测模型.将数据分成后training
和testing
数据集的基础上,感兴趣的结果(本文件标记y
,但实际上是在classe
数据集中的变量):
inTrain <- createDataPartition(y = data$y, p = 0.75, list = F)
training <- data[inTrain, ]
testing <- data[-inTrain, ]
Run Code Online (Sandbox Code Playgroud)
我尝试了两种不同的方法:
modFit <- caret::train(y ~ ., method = "rpart", data = training)
pred <- predict(modFit, newdata = testing)
confusionMatrix(pred, testing$y)
Run Code Online (Sandbox Code Playgroud)
与
modFit <- rpart::rpart(y ~ ., data = training)
pred <- predict(modFit, newdata = testing, type = "class")
confusionMatrix(pred, testing$y)
Run Code Online (Sandbox Code Playgroud)
我假设它们会给出相同或非常相似的结果,因为初始方法加载'rpart'包(建议我使用此包用于该方法).但是,时间(caret
慢得多)和结果是非常不同的:
Method 1 (caret)
:
Confusion Matrix and …
Run Code Online (Sandbox Code Playgroud) 我想使用ggplot创建一个类似于下面的色盲测试.
基本思想是使用geom_hex
(或者可能是voronoi图,或者甚至可能是上图中的圆圈)作为起始点,并定义一个数据帧,当在ggplot中绘制时,生成图像.
我们首先要创建一个数据集,例如:
df <- data.frame(x = rnorm(10000), y = rnorm(10000))
Run Code Online (Sandbox Code Playgroud)
然后绘制这个:
ggplot(df, aes(x, y)) +
geom_hex() +
coord_equal() +
scale_fill_gradient(low = "red", high = "green", guide = FALSE) +
theme_void()
Run Code Online (Sandbox Code Playgroud)
如下图所示:
主要的缺失步骤是创建一个实际绘制有意义的符号(字母或数字)的数据集,并且我不确定如何在没有精心绘制坐标的情况下最好地进行此操作.理想情况下,人们可以从图像文件中读取坐标.
最后,稍微整理一下可以通过去除外围点来围绕绘图边缘.
非常欢迎所有的建议!
更接近我所追求的,我们可以使用下面的字母'e':
使用该imager
包,我们可以读取它并将其转换为数据帧:
img <- imager::load.image("e.png")
df <- as.data.frame(img)
Run Code Online (Sandbox Code Playgroud)
然后绘制该数据帧使用geom_raster
:
ggplot(df, aes(x, y)) +
geom_raster(aes(fill = value)) +
coord_equal() +
scale_y_continuous(trans = scales::reverse_trans()) +
scale_fill_gradient(low = "red", high = "green", guide = FALSE) +
theme_void()
Run Code Online (Sandbox Code Playgroud)
如果我们使用geom_hex
而不是geom_raster …
我正在使用RStudio knitr
等来制作可重复的报告,并希望我能为Word文档和PDF提供最好的版本 - 我更喜欢使用LaTeX,但最终用户倾向于更喜欢可编辑Word文档的灵活性.
我写了一个ifelse
声明,基本上说"如果这是render
作为word文档编辑,kable
在markdown中创建一个表,否则kable
在LaTeX中创建表,然后操作以使表看起来更好(阴影行等)'.
我不明白rmarkdown::render
ing过程是如何捕获的output_format
,但是有没有办法将它存储为变量并在ifelse
语句中使用?
最小的例子是将此代码保存为test.Rmd
:
format <- output_format #(somehow captured as a variable)
printTable <- function(data = df, format = format){
if (format %in% 'pdf_document') {
# create nice latex table
} else {
# create markdown table
}
}
Run Code Online (Sandbox Code Playgroud)
然后,在运行此代码时:
rmarkdown::render(input = "test.Rmd", output_format = c("word_document", "pdf_document"))
Run Code Online (Sandbox Code Playgroud)
报告的不同版本将包含正确的表格.
我正在尝试构建一些函数来从问卷创建标准表,使用dplyr进行数据操作.这个问题对于group_by函数非常有用,它传递参数(在这种情况下,我想用来制作表的变量的名称)(...)
,但是当试图将相同的参数传递给其他dplyr命令时,这似乎会中断,特别是'选择'和'过滤'.我得到的错误信息是'...' used in an incorrect context'
.
有没有人对此有任何想法?谢谢
为了完整性(以及任何其他提示 - 我是编写函数的新手),这里是我想要使用的代码:
myTable <- function(x, ...) {
df <-
x %>%
group_by(Var1, ...) %>%
filter(!is.na(...) & ... != '') %>% # To remove missing values: Not working!
summarise(value = n()) %>%
group_by(Var1) %>%
mutate(Tot = sum(value)) %>%
group_by(Var1, ...) %>%
summarise(num = sum(value), total = sum(Tot), proportion = num/total*100) %>%
select(Var1, ..., proportion) # To select desired columns: Not working!
tab <- dcast(df, Var1 ~ ..., …
Run Code Online (Sandbox Code Playgroud) 我正在使用 RStudio 开发的新传单包部署一个 Shinyapp。关于某些元素的在线文档似乎并不多 - 就我而言,我需要指定图例显示因子级别的顺序。通常,我会通过在绘图命令之前指定级别来执行此操作(例如在 ggplot2 中):
df$name <- factor(df$name, levels = sort(df$name))
Run Code Online (Sandbox Code Playgroud)
但是,这似乎不适用于传单中的图例。下面是一个 MWE(NB Africa geojson 文件可以在这里下载)。您将看到图例顺序不是按字母顺序排序的,正如人们通常所期望的那样。我的问题是如何做到这一点。
library(shiny)
library(leaflet)
map_africa <- rgdal::readOGR("africa.geo.json", "OGRGeoJSON")
map_africa$name <- factor(map_africa$name, levels = sort(map_africa$name))
ui <- bootstrapPage( leafletOutput("map") )
server <- function(input, output, session) {
pal <- colorFactor('RdYlBu', map_africa$name)
output$map <- renderLeaflet({
leaflet(map_africa) %>%
addPolygons(stroke = F,
fillColor = ~pal(name),
popup = ~name) %>%
addLegend(position = 'topright',
colors = ~pal(name),
labels = ~name)
})
}
shinyApp(ui, server)
Run Code Online (Sandbox Code Playgroud) 我正在 RMarkdown 文档中的循环内创建一系列绘图,然后将其编织成 PDF。我可以毫无问题地做到这一点,但我希望标题能够反映每个图之间的变化。MWE 如下所示:
---
title: "Caption loop"
output: pdf_document
---
```{r, echo=FALSE}
library(tidyverse)
p <-
map(names(mtcars), ~ggplot(mtcars) +
geom_point(aes_string(x = 'mpg', y = .))) %>%
set_names(names(mtcars))
```
```{r loops, fig.cap=paste(for(i in seq_along(p)) print(names(p)[[i]])), echo=FALSE}
for(i in seq_along(p)) p[[i]] %>% print
```
Run Code Online (Sandbox Code Playgroud)
我第一次尝试捕获绘图并将其存储在变量中p
,并尝试使用它来生成标题,但这不起作用。尽管这肯定是很多人需要做的事情,但我在 SO 上还没有找到太多相关信息。我确实找到了这个问题,但它看起来太复杂了,我想知道是否有一个我缺少的清晰而简单的解决方案。
eval.after
我想知道它是否与此问题有关,但这不涉及循环内生成的图。
非常感谢您的帮助!
我正在尝试使用 {ggplot2}、{osmdata} 和 {sf} 绘制日内瓦湖/莱曼湖。每当我尝试绘制湖泊多面体(其中有 5 个)时,都会出现错误。我在其他地方找不到任何提到这个错误的地方。
library(osmdata)
#> Data (c) OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright
library(tidyverse)
lake_gva <-
getbb("Geneva") %>%
opq()%>%
add_osm_feature(key = "natural", value = "water") %>%
osmdata_sf()
lake_gva
#> Object of class 'osmdata' with:
#> $bbox : 46.1777724,6.1102411,46.231885,6.1758527
#> $overpass_call : The call submitted to the overpass API
#> $meta : metadata including timestamp and version numbers
#> $osm_points : 'sf' Simple Features Collection with 22394 points
#> $osm_lines : 'sf' Simple Features Collection with 320 linestrings …
Run Code Online (Sandbox Code Playgroud) 我正在尝试将部分幻灯片添加到rmarkdown
使用latex命令编写的beamer演示文稿中\section{}
.但是,它会在转换期间自动插入到\begin{frame}
&之间\end{frame}
,这会导致编译失败.有没有办法阻止这种情况发生,以便可以添加部分幻灯片而无需手动编辑tex
文件?
这是我的rmarkdown
代码:
---
title: "Beamer presentation"
output: beamer_presentation
---
\section{Section one}
Run Code Online (Sandbox Code Playgroud)
转换为:
\title{Beamer presentation}
\begin{document}
\frame{\titlepage}
\begin{frame}
\section{Section one}
\end{frame}
\end{document}
Run Code Online (Sandbox Code Playgroud) 我有一个特定顺序的数据帧:
df <-
data.frame(
foo = 1:3,
bar = LETTERS[1:3],
baz = rnorm(3)
)
df
foo bar baz
1 1 A 0.41474174
2 2 B -0.08416768
3 3 C -0.27931232
Run Code Online (Sandbox Code Playgroud)
在另一个数据框中,我将旧的变量名称与一些新名称匹配,但顺序不同:
variable_match <-
data.frame(
old = names(df)[c(2, 3, 1)],
new = LETTERS[1:3]
)
variable_match
old new
1 bar A
2 baz B
3 foo C
Run Code Online (Sandbox Code Playgroud)
我的问题是:如何通过在第二个数据帧中查找相应的值来重命名原始数据框中的变量.我理想地寻找tidyverse
解决方案.我尝试过各种变化:
library(tidyverse)
df %>% rename_at(variable_match$old, funs(variable_match$new))
Run Code Online (Sandbox Code Playgroud)
假设rename_at是正确的方法,但这不起作用.我想知道是否purrr::map_*
是正确的方法,但不知道如何.非常感谢你的建议.