可以将以下代码复制并粘贴到RStudio中并运行:
salary <- c(45434,54834, 685485)
name <- c("john smith", "willy mcghee", "john paul stevens")
df <- data.frame(salary, name)
library(shiny)
library(dplyr)
# Define UI for application that draws a histogram
ui <- fluidPage(
# Title
titlePanel("title"),
# this is the sidebar on the left when you run
sidebarLayout(
sidebarPanel(
# selection of names
selectInput("people",
label = "select the investor",
choices = c("john smith", "willy mcghee", "john paul stevens"))
),
mainPanel(
helpText("main panel text"),
textOutput("textsummary")
)
)
)
# Define server logic required to draw a histogram
server <- function(input, output) {
vals <- reactiveValues()
observe({
vals$people <- input$people
vals$famousNetWorth <- df %>% filter(name == input$people)
} )
output$textsummary <- renderText({
paste(" the salary for ",vals$people, " is ", vals$famousNetWorth)
})
}
# Run the application
shinyApp(ui = ui, server = server)
这是我得到的输出:
问题
为什么输出打印两次(以黄色突出显示)?问题肯定源于尝试从我的salary
中的df
列中选择值以匹配用户选择的名称&#39;除了我努力寻找更好的名称反应方式选择与name
输入匹配的工资。下一张图片是硬编码的 - 这就是我想要的样子:
答案 0 :(得分:2)
这发生了(正如评论中提到的@greg L)filter
步的输出仍然是data.frame
,其中有两列,如原始'df'。
df %>%
filter(name == "john smith")
# salary name
#1 45434 john smith
使用paste
,它会遍历每一列,并paste
带有列值的'salary:'字符串
paste("salary:", df %>%
filter(name == "john smith"))
#[1] "salary: 45434" "salary: 2"
如果我们看第二个案例,看起来很困惑,但请查看'df'的str
str(df)
#'data.frame': 3 obs. of 2 variables:
# $ salary: num 45434 54834 685485
# $ name : Factor w/ 3 levels "john paul stevens",..: 2 3 1
由于'name'为factor
类,因此存储模型为integer
df$name
#[1] john smith willy mcghee john paul stevens
# Levels: john paul stevens john smith willy mcghee
或查看levels
levels(df$name)
#[1] "john paul stevens" "john smith" "willy mcghee"
“约翰史密斯”是第二级
df %>%
filter(name == "john smith") %>%
pull(name) %>%
as.integer
#[1] 2
paste
factor
被强制转换为整数存储模式
我们需要pull
“薪水”栏中的vector
,即
vals$famousNetWorth <- df %>%
filter(name == input$people) %>%
pull(salary)
-full code
salary <- c(45434,54834, 685485)
name <- c("john smith", "willy mcghee", "john paul stevens")
df <- data.frame(salary, name)
library(shiny)
library(dplyr)
# Define UI for application that draws a histogram
ui <- fluidPage(
# Title
titlePanel("title"),
# this is the sidebar on the left when you run
sidebarLayout(
sidebarPanel(
# selection of names
selectInput("people",
label = "select the investor",
choices = c("john smith", "willy mcghee", "john paul stevens"))
),
mainPanel(
helpText("main panel text"),
textOutput("textsummary")
)
)
)
# Define server logic required to draw a histogram
server <- function(input, output) {
vals <- reactiveValues()
observe({
vals$people <- input$people
vals$famousNetWorth <- df %>%
filter(name == input$people) %>%
pull(salary)
} )
output$textsummary <- renderText({
paste(" the salary for ",vals$people, " is ", vals$famousNetWorth)
})
}
# Run the application
shinyApp(ui = ui, server = server)
-output