嗨,闪亮的用户,
我希望我的用户能够在主数据框架中添加新的变量。用户将使用textInput键入定义。然后,我们将使用server.R将其添加到数据框架中。我无法使它发挥作用。任何帮助都将不胜感激。谢谢!
Rawdata:
colA <- c('1','2','3','3','2')
colB <- c('1','1','3','3','2')
colC <- c('14','12','33','33','26')
colD <- c('Value','Mainstream','Value','Premium','Premium')
colE <- c(1,2,3,4,5)
rawdata <- as.data.frame(cbind(colA,colB, colC, colD, colE))
View(rawdata)
ui.R:
fluidPage(
sidebarLayout(
sidebarPanel(
textInput("addVar", "New attribute definition"),
helpText("Note: Type the attribute definition using R code."),
helpText("For example:"),
helpText("data$Value <- ifelse (data$price_tiers_new == 'Value', 1, 0)"),
br(),
actionButton("addButton", strong("Add!")),
width = 3
),
mainPanel(
verticalLayout(
br()
#Will display histogram of the newly added variables
)
)
)
)
服务器。R:
function(input, output, session) {
curr <- reactiveValues()
curr$df <- rawdata
observeEvent(input$addButton, {
eval(parse(text=input$filter))
})
}
例如,这里有两个新的变量定义要尝试。如果我们添加第一个定义,rawdata将有一个额外的列(值)。如果我们添加第二个定义,rawdata将有两个额外的列(Value和Premium)。
curr$df$Value <- ifelse(curr$df$colD == 'Value', 1, 0)
curr$df$Premium <- ifelse(curr$df$colD == 'Premium', 1, 0)
发布于 2017-09-08 15:20:21
尽管对这个问题有一个公认的答案,但是值得注意的是,如果不小心使用,eval(parse())
有很大的风险(例如:按原样评估传入的文本。参见关于eval(parse())
的讨论)。
规避这些风险的一种方法是对传入的文本进行变异(双关非故意),并对变异的文本进行eval(parse())
。这样,您就可以得到预期的结果或错误,但几乎不会像运行长代码那样,比如使用T <- FALSE
(感谢@flodel)或其他一些植入的bug来运行。
例如:input_vector
和name_vector
分别是新变量定义条件和新变量名的列表。
input_vector <- list()
input_vector[[1]] <- "ifelse(am == 1, 'wohoo', 'io')"
input_vector[[2]] <- "vs == 1"
input_vector[[3]] <- "cyl >= 6"
input_vector[[4]] <- "0"
name_vector <- list()
name_vector[[1]] <- "automatic_"
name_vector[[2]] <- "VS_Equals_1_"
name_vector[[3]] <- "HighCylinder_"
name_vector[[4]] <- "Blank_"
new_var_count <- 1:4
mutated_data <- reactive({
mt %>%
{eval(parse(text=
paste0("mutate_(.,",
paste0(name_vector, as.character(new_var_count),"= input_vector[[",
as.character(new_var_count), "]]", collapse= " , "),
")"
)
))}
})
https://stackoverflow.com/questions/44598544
复制相似问题