【发布时间】:2021-03-28 14:21:03
【问题描述】:
我正在尝试做一些在 R 脚本中很容易实现的事情,但是当成为 Shiny 应用程序的一部分时,我正在努力复制。我正在使用“reactive({})”读取文件(下面提供的测试代码中的这部分已替换为测试数据集,第 13-16 行)。我想获取变量“物种”条目并将它们分配给数据框行名。我尝试了两种方法
-
在“reactive({})”语句中,第 13-16 行
-
通过创建一个新的数据框 df1,第 18-20 行
但由于某种原因,这两种方法都行不通。
非常感谢您!
library(shiny)
library(DT)
library(datasets)
ui <- basicPage("",
DT::dataTableOutput("table"),
verbatimTextOutput("head1"),
verbatimTextOutput("head2")
)
server <- function(input, output, session) {
df <- reactive({
df <- data.frame(v1=c("a", "b"), v2=c(10,20))
# row.names(df) <- df[,1] # THIS DOES NOT WORK
})
df1 <- reactive({ # THIS ALSO DOESN'T WORK
row.names(df()) <- df()[,1]
})
# Show data in a table ----
output$table <- DT::renderDataTable({
datatable(
{df()},
filter = 'top',
class="cell-border stripe",
rownames = TRUE
) # end of datatable
})
output$head1 <- renderPrint({
head(df())
})
output$head2 <- renderPrint({
head(df1())
})
}
shinyApp(ui = ui, server = server)
【问题讨论】:
-
你确定它在 R 中工作没有闪亮吗?我收到不允许双行名称(非唯一)的错误,请尝试例如与
testdf <- iris; row.names(testdf) <- testdf$Species -
@starja - 嗯,你是对的,一定与数据集有关,因为这个工作:``` r df v1 v2 #> 1 a 10 #> 2 b 20 df v1 v2 #> aa 10 #> bb 20 ``` 由reprex package (v0.2.1) 于 2020-12-17 创建跨度>
-
@starja - 我将原始问题中的数据框更改为在使用 R 脚本时可以正常工作但作为 Shiny 实现失败的数据框。不知道为什么 iris 数据集表现不同。