Im trying to create a function that imports my data into R. Whenever I call this function though it runs through it but I don't see my data set anywhere
inputData <- function(){
teams <- read.csv('C:/Users/BT_1N3_24/Desktop/PremierLeaguePlayers.csv', header = TRUE)
currentTeam <- read.csv('C:/Users/BT_1N3_24/Desktop/TeamStats.csv', header = TRUE)
}
All functions are locally scoped in R. If you want to pass something out of the environment, it must be returned as an object. I would write your code like this:
inputData <- function(){
teams <- read.csv('C:/Users/BT_1N3_24/Desktop/PremierLeaguePlayers.csv', header = TRUE)
currentTeam <- read.csv('C:/Users/BT_1N3_24/Desktop/TeamStats.csv', header = TRUE)
list(teams, currentTeam)
}
## call the function
data.list <- inputData()
Related
I'm getting this error when I run below code, can anyone please tell how to overcome this error.
Below is the code in which mydata is the main data set and I have created a shiny dashboard using the below code.
I tried to make one of the column as URL , but its showing error as in title.
And I tried giving data()$IFX_USERNAME as in his is a very common error in shiny apps. This most typically appears when you create an object such as a list, data.frame or vector using the reactive() function – that is, your object reacts to some kind of input. If you do this, when you refer to your object afterwards, you must include parentheses.
For example, let’s say you make a reactive data.frame like so:
MyDF<-reactive({ code that makes a data.frame with a column called “X” })
If you then wish to refer to the data.frame and you call it MyDF or MyDF$X you will get the error. Instead it should be MyDF() or MyDF()$X You need to use this naming convention with any object you create using reactive(), even then its showing the same error
library("shiny")
library("datasets")
library("DT")
library("shinyBS")
library(tidyr)
lapply( dbListConnections( dbDriver( drv = "MySQL")), dbDisconnect)
#connecting to database
dbListTables(mydb)
dbListFields(mydb, 'DL_COMMUNITY')
rs = dbSendQuery(mydb, "select * from DL_COMMUNITY")
mydatabase=fetch(rs)
setDT(mydatabase)
colnames(mydatabase)
header <- dashboardHeader()
ui = shinyUI(fluidPage(
DT::dataTableOutput("mtcarsTable"),
bsModal("mtCarsModal", "My Modal", "",dataTableOutput('mytext'), size = "large")
))
on_click_js = "
Shiny.onInputChange('mydata', '%s');
$('#mtCarsModal').modal('show')
"
on_click_js1 = "
Shiny.onInputChange('mydata', '%s');
$('#mtcarsTable').modal('show')
"
convert_to_link = function(x) {
as.character(tags$a(href = "#", onclick = sprintf(on_click_js,x), x))
}
convert_to_link1 = function(x) {
as.character(tags$a(href = "#", onclick = sprintf(on_click_js1,x), x))
}
shinyApp(
ui = ui,
server = function(input, output, session) {
mtcarsLinked <- reactive({
mydatabase$IFX_USERNAME <- sapply(
mydatabase$IFX_USERNAME,convert_to_link)
return(mydatabase)
})
**linked <- reactive({
myd$TEAM_MEMBERS <- sapply(
myd$TEAM_MEMBERS,convert_to_link1)
return(myd)
})**
output$mtcarsTable <- DT::renderDataTable({
DT::datatable(mtcarsLinked(),
class = 'compact',
escape = FALSE, selection='none'
)
})
output$mytext = DT::renderDataTable({
#userQuery=paste("select PROJECT,COMMENT from DL_COMMUNITY where IFX_USERNAME = '",user,"'",sep="")
#rs = dbSendQuery(mysqlCon,userQuery)
userQuery=paste("SELECT *
from Heatmap.DL_PROJECT where CONCAT(',', TEAM_MEMBERS, ',') like '%,sa,%'
or PROJECT_OWNER like '%,sa,%'
or PROJECT_LEAD like '%,sa,%'")
rs = dbSendQuery(mydb,userQuery)
myd=fetch(rs,n=-1)
myd<-data.frame(myd)
myd$TEAM_MEMBERS<- as.list(strsplit(myd$TEAM_MEMBERS, ","))
#myd<-myd %>%
#mutate(TEAM_MEMBERS = strsplit(as.character(TEAM_MEMBERS), ",")) %>%
#unnest(TEAM_MEMBERS)
#setDT(myd)
#hello <- input$mydata
#myd<-mydatabase[mydatabase$IFX_USERNAME==input$mydata,]
#myd1<-t(myd)
DT::datatable(linked(),
class='compact',
escape = FALSE,selection = 'none')
})
}
)
First, always use my_reactive() when you call a reactive function e.g. my_reactive.
Second, the object of type closure not subsettable usually means that the object you want to subset (here with $) cannot be found. You are not having the object not found error because you gave it a name already known to R.
As in the example of jogo, the same error occurs when trying to subset mean. mean is an object in R so it exists and R will not return object not found but it is a function and you cannot subset from it hence the error object is not subsettable.
Compare the results of the following lines of code.
mean[1]
mean <- c(1, 3)
mean[1]
Also note that R can still use mean to perform the mean of a numeric vector as it knows when to look for a function or for something else. But it is strongly advised not to do that. You should always properly name your objects with meaningful names.
Hi I am trying to run a r script
loadData <- function()
{
library(XLConnect)
excel0157 <- loadWorkbook("C:\\Users\\\\Documents\\R\\data\\0157\\0157.xlsx")
sheet_names <- getSheets(excel0157)
c0157 <- readWorksheetFromFile("C:\\Users\\\\Documents\\R\\data\\0157\\0157.xlsx",sheet = sheet_names[1],region = "B4:B27", header = FALSE)
for (i in 1:79) {
c0157[i] <-readWorksheetFromFile("C:\\Users\\\\Documents\\R\\data\\0157\\0157.xlsx",sheet = sheet_names[i],region = "B4:B27", header = FALSE)
}
c0157ts1 <- as.numeric(c(t(c0157)))
}
However, c0157ts1 does not create. If I run the c0157ts1 <- as.numeric(c(t(c0157))) in the console, c0157ts1 is created.
Can anyone explain why?
Context
I need to use R metaprogramming for use with the framework Shiny, as their modules and event handlers depend on metaprogramming for passing expressions and executing it in the right context for evaluation to chain with pre-defined input, output, and session objects.
To simplify the problem, I'm going to use the example of a source() function.
Example
To run Shiny, Shiny requires two objects: ui and server. The server is a function: server <- function(input, output, session).
All I want to do is this:
server <- function(input, output, session) {
source('fileA.R', local=TRUE)
source('fileB.R', local=TRUE)
}
This works on its own. However, I have about ten different files to include. So I created a function to return the required code to execute within it:
run_server <- function(str) {
names <- strsplit(x=str, split='/')
code <- character()
for (i in 1:length(names)) {
module_names <- ''
filenames <- ''
module_names[i] <- names[[i]][length(names[[i]])]
filenames[i] <- paste0(str[i], '/server_', module_names[i], '.R')
code <- paste0(code, "source(\'", filenames[i], "\'", ", local = TRUE)", "\n")
}
return(parse(text=code))
}
This works fine... except that it returns the type expression from R, which is different than the return type of quote or substitute. It also means that if I try to use eval/evalq on this, it doesn't work the way I expect.
I've resorted to trying to create the server function using another helper function:
make_server <- function(...) {
code <- eval(substitute(...))
func <- bquote(function(input, output, session) {
.(code)
})
return(
func
)
}
But once again, the function body is a bit weird--it still has the expression() function wrapped around the contents of its body:
function(input, output, session) {
expression(source("modules/upload_rds/server_upload_rds.R",
local = TRUE), source("modules/download_rds/server_download_rds.R",
local = TRUE), source("modules/fileupload/server_fileupload.R",
local = TRUE), source("modules/normalization/server_normalization.R",
local = TRUE), source("modules/outlier_zmedian/server_outlier_zmedian.R",
local = TRUE), source("modules/basic_nmf/server_basic_nmf.R",
local = TRUE), source("modules/monocle/server_monocle.R",
local = TRUE), source("modules/deseq2/server_deseq2.R",
local = TRUE), source("modules/fem_analysis/server_fem_analysis.R",
local = TRUE), source("modules/topGO/server_topGO.R",
local = TRUE), source("modules/cluster_profiler/server_cluster_profiler.R",
local = TRUE), source("modules/scde/server_scde.R", local = TRUE),
source("modules/edgeR/server_edgeR.R", local = TRUE))
}
And this doesn't evaluate as if the code was simply copy-pasted or truly substituted like a C preprocessor would.
expression() vs. quote()
Reading this answer here, it appears that an expression is a vector of calls, etc. So the natural thing to do would be to just apply something like unlist() or c(). But this doesn't work. Does anyone have a solution to this?
I just started with tcltk and R. And I am having troubles accessing a computed value by a function called myFun1 when calling a second function myFun2:
Here is a simplified version of my UI:
Simple tcltk interface
library(tcltk)
tt <- tktoplevel()
topMenu <- tkmenu(tt)
tkconfigure(tt, menu = topMenu)
fileMenu <- tkmenu(topMenu, tearoff = FALSE)
tkadd(fileMenu, "command", label = "Function1", command = myFun1)
tkadd(fileMenu, "command", label = "Function2", command = myFun2)
tkadd(topMenu, "cascade", label = "Tab", menu = fileMenu)
tkfocus(tt)
My functions
myFun1 <- function() {
compVal <- 2*3
compVal
}
myFun2 <- function() {
msg <- paste("The value is: \n", compVal )
mbval<- tkmessageBox(title="This is the title",
message=msg,type="yesno",icon="question")
}
Calling myFun1 works, but myFun2 returns
Error in paste("The value is: \n", compVal) :
Object 'compVal' not found
Also wrapping compVal into return(compVal) doesn`t work.
I was also thinking of doing:
res <- list(compVal=compVal)
but I am not able to access the created list with myFun2.
Any sugesstions on how to access the returned value form myFun1 inside myFun2?
I found a solution, at first I thought its not really a "clean" way of doing it, but even in the offical documentation it is done this way.
Simply create a global variable using <<- :
myFun1 <- function() {
compVal <<- 2*3
}
I want to save user created filters from Data.Tables for later use. Particularly, I would like to determine what sorting and searches were done. If I am reading the Shiny code on GitHub correctly the user inputs to Data.Tables are used to generate a JSON file in function dataTablesJSON (utils.R). What would be the best way to access these parameters from inside a Shiny app? I tried a number of things but no luck sofar. Latest attempt below:
output$showSession <- renderPrint({
murl <- session$registerDataObj(
name = "MyTest",
data = getdata(), # a function in my app that gets the 'active' dataset
filter = function(data, req) {
params <- URLdecode(rawToChar(req$rook.input$read()))
q <- parseQueryString(params, nested = TRUE)
}
)
print(murl)
})
# output from function above (not affected by inputs to Data.Tables)
[1] "session/1905f776d40a0b94a439ec3121796a9c/dataobj/MyTest?w="
# First few lines from function dataTablesJSON that gets the inputs I want
dataTablesJSON <- function(data, req) {
n <- nrow(data)
# DataTables requests were sent via POST
params <- URLdecode(rawToChar(req$rook.input$read()))
q <- parseQueryString(params, nested = TRUE)
.....