Error in inference function in frbs package - R - r

I am trying to implement a fuzzy inference system in R using frbs package.
Here is my code -
varinp.mf <- matrix(c(1,1,1,1,3,1,1,4,3,1,1,1,1,3,1,4,4,3,
0,20,40,70,85,0,5,30,65,0,25,40,70,85,0,20,45,70,
15,35,65,85,95,5,25,45,90,20,30,50,75,95,15,30,50,90,
30,45,75,90,0,10,35,65,90,30,45,75,90,100,25,40,65,100,
0,0,0,0,0,0,0,75,100,0,0,0,0,0,0,50,75,0
), nrow=5, byrow=TRUE)
## Define number of linguistic terms of input variables.
num.fvalinput <- matrix(c(5, 4, 5, 4), nrow=1)
varinput.1 <- c("veryPoor", "Poor", "Average","Good","veryGood")
varinput.2 <- c("Less", "Average", "Many", "aLot")
varinput.3 <- c("veryPoor", "Poor", "Average","Good","veryGood")
varinput.4 <- c("Less", "Average", "More","High")
names.varinput <- c(varinput.1, varinput.2, varinput.3, varinput.4)
## Set interval of data.
range.data <- matrix(c(0, 100, 0, 100, 0, 100, 0, 100, 0, 100), nrow = 2)
## Define inference parameters.
## Detailed information about values can be seen in the inference function.
type.defuz <- "WAM"
type.tnorm <- "MIN"
type.snorm <- "MAX"
type.implication.func <- "ZADEH"
## Give the name of simulation.
name <- "Sim-0"
## the names of variables
colnames.var <- c("Hotel_Facility_Score", "Visited_Count", "Room_facility_score", "Average_price", "Relative_Class")
## Define number of linguistic terms of output variable.
## In this case, we set the number of linguistic terms to 3.
num.fvaloutput <- matrix(c(5), nrow = 1)
## Give the names of the linguistic terms of the output variable.
varoutput.1 <- c("veryGood", "Good", "Average","Poor","veryPoor")
names.varoutput <- c(varoutput.1)
## Define the shapes and parameters of the membership functions of the output variables.
varout.mf <- matrix(c(5,5,5,5,5,
95,75,55,35,20,
4,8,5,7,5,
0,0,0,0,0,
0,0,0,0,0),
nrow = 5, byrow = TRUE)
## Define the fuzzy IF-THEN rules;
rule <- matrix(
c("veryGood", "and", "aLot", "and", "veryGood", "and", "less", "->", "veryGood",
"veryGood", "and", "Many", "and", "veryGood", "and", "Average", "->", "veryGood",
"veryGood", "and", "aLot", "and", "veryGood", "and", "Average", "->", "Good",
"veryGood", "and", "aLot", "and", "veryGood", "and", "Less", "->", "Good",
"Good", "and", "Many", "and", "Good", "and", "Less", "->", "Good",
"Good", "and", "aLot", "and", "Good", "and", "Average", "->", "Good",
"Average", "and", "aLot", "and", "Good", "and", "Less", "->", "Average",
"veryGood", "and", "Average", "and", "veryGood", "and", "More", "->", "Average",
"Good", "and", "Many", "and", "Good", "and", "Average", "->", "Average",
"Average", "and", "Average", "and", "Average", "and", "More", "->", "Poor",
"Good", "and", "Many", "and", "vGood", "and", "High", "->", "Poor",
"Average", "and", "Average", "and", "Average", "and", "High", "->", "Poor",
"Poor", "and", "Less", "and", "Poor","and", "High", "->", "veryPoor",
"veryPoor", "and", "Less", "and", "veryPoor", "and", "High", "->", "veryPoor"),
nrow = 14, byrow = TRUE)
## Set type of model which is "MAMDANI".
type.model <- "MAMDANI"
## Generate a fuzzy model with frbs.gen.
object <- frbs.gen(range.data, num.fvalinput, names.varinput,
num.fvaloutput, varout.mf, names.varoutput, rule,
varinp.mf, type.model, type.defuz, type.tnorm,
type.snorm, func.tsk = NULL, colnames.var, type.implication.func, name)
## Plot the membership function.
plotMF(object)
newdata <- matrix(c(15, 80, 85, 85, 45, 75, 78, 70), nrow = 2, byrow = TRUE)
## Fuzzification Module:
num.varinput <- ncol(num.fvalinput)
MF <- fuzzifier(newdata, num.varinput, num.fvalinput, varinp.mf)
## Check input data given by user.
ruleb <- rulebase(type.model, rule, func.tsk = NULL)
## Inference Module:
miu.rule <- inference(MF, ruleb, names.varinput, type.tnorm, type.snorm)
I am getting this error -
miu.rule <- inference(MF, ruleb, names.varinput, type.tnorm, type.snorm)
Error in MF[k, temp[j + 2]] : subscript out of bounds
I took help from the example give at this link -
http://www.inside-r.org/packages/cran/frbs/docs/frbs.gen
But the example runs fine. I am not able to find what is the error in my code.

I found a way to block the error: decrease your rule list down to 3 elements as in the example :-(.
But still don't know why!
BTW creating some additional rules (up to 5) in the example doesn't trigger error.
Edit 16/07/19: I don't retest the whole stuff but this is surely linked to the data/structure format.
Look the data/structure format of the example and stick thoroughly to this format for every data/structure you create and send to the package. This should solve your current error.

Related

Editing loop to append output by variable

The script below is used to create a loop, create certain outputs and separately export them. I would like to modify the script to append the variables of interest by their stratifiers - i.e. combine health_mental, overall_health and outlook_life outputs when they're stratified by age, and another output when they're stratified by sex. I would like to then export those files out in excel format. Thanks in advance for the help!
library(tidyverse)
library(dplyr)
df <- data.frame (overall_health = c("poor", "good", "excellent", "poor", "good", "poor", "poor", "excellent"),
outlook_life = c("good", "excellent", "excellent", "poor", "excellent", "poor", "excellent", "poor"),
health_mental = c("poor", "poor", "excellent", "poor", "poor", "poor", "excellent", "good"),
sex = c("F", "M", "M", "F", "F", "M", "F", "M"),
age_group = c("50-54", "60-64", "80+", "70-74", "40-44", "45-49", "60-64", "65-69"),
income = c("$<40,000", "$50,000-79,000", "$80,000-110,000", "$111,000+", "$<40,000", "$<40,000", "$50,000-79,000", "$80,000-110,000"),
education = c("HS", "College", "Bachelors", "Masters", "HS", "College", "Bachelors", "Masters"),
geography= c("area1", "area2", "area1", "area2", "area2", "area1", "area2", "area1"))
geos <- unique(df$geography)
vars <- c("health_mental", "overall_health", "outlook_life")
combinations <- expand.grid(c("age_group", "sex"), vars, stringsAsFactors = F)
combinations$label <- paste(combinations$Var1, combinations$Var2, sep = "_")
output <- list()
for (geo in geos){
for (combo in 1:nrow(combinations)){
output_label <- paste(combinations[[combo,"label"]],geo,sep="_")
temp <- df %>%
filter(geography == geo) %>%
group_by_at(combinations[combo,1:2] %>% unlist()%>%unname()) %>%
summarise(count = n(),
total = nrow(.),
proportion = count/nrow(.) *100)
output[[output_label]] <- temp
}
}
Expected output - example

Creating a tdm with only one variable

So I need to prepare a term-document-matrix for each of the sets of text I want to subsequently run against each other in a classification procedure (rolling.classify() in Stylo package).
So I created a tdm of the whole text corpus, then want to make two sets only of selected texts, one which should contain one text only. So multiple texts works fine (a), but one texts only does not (b), I cannot do this?
freq.list <- make.frequency.list(words, head = 265) # Creating frequency list using only the frequencies of the
# selected features from word-list (words)
word.frequencies <- make.table.of.frequencies(corpus = x, features = freq.list)
# Document-term matrix of whole corpus and matching frequencies.
# Making two subsets now:
a <- word.frequencies[c(1,2,3,17,19,20,21,22,23), 1:263]
dim(a) # Double-check that it is the right no. of texts
b <- word.frequencies[18,1:263]
dim(b) # Double-check
> dim(a)
[1] 9 263
> dim(b)
NULL
data:
(used dput())
x <- structure(list(middleFr_Calmative_1946 = c("the", "calmative",
"i", "don’t", "know", "when", "i", "died", ".", "it", "always",
"seemed", "to", "me", "i", "died", "old", ",", "about", "ninety",
"years", "old", ",", "and", "what", "years", ",", "and", "that",
"my", "body", "bore", "it", "out", ",", "from", "head", "to",
"foot", ".", "but", "this", "evening", ",", "alone", "in", "my",
"icy", "bed", ",", "i", "have", "the", "feeling", "i’ll", "be",
"older", "than", "the", "day", ",", "the", "night", ",", "when",
"the", "sky", "with", "all", "its", "lights", "fell", "upon",
"me", ",", "the", "same", "i", "had", "so", "often", "gazed",
"resolved", "to", "speak", "to", "him", ".", "so", "i", "marshalled",
"the", "words", "and", "opened", "my", "mouth", ",", "thinking",
"i", "would", "hear", "them", ".", "but", "all", "i", "heard",
"was", "a", "kind", "of", "rattle", ",", "unintelligible", "even",
"have", "a", "penny", "in", "my", "pocket", ",", "nor", "anything",
"resembling", "it", "."), middleFr_End_1946 = c("the", "end",
"they", "clothed", "me", "and", "gave", "me", "money", ".", "i",
"back", "mine", ".", "i", "added", ",", "give", "me", "back",
"my", "greatcoat", ".", "they", "replied", "that", "they", "had",
"burnt", "them", ",", "together", "with", "my", "other", "clothes",
".", "i", "understood", "then", "that", "the", "end", "was",
"near", ",", "at", "least", "fairly", "near", ".", "later", "on",
"i", "tried", "to", "exchange", "this", "hat", "for", "a", "cap",
",", "or", "a", "slouch", "which", "could", "be", "pulled", "down",
"over", "my", "face", ",", "but", "without", "much", "success",
".", "and", "yet", "i", "could", "not", "go", "about", "bare",
"-", "headed", ",", "with", "my", "skull", "in", "the", "state",
"it", "was", ".", "at", "first", "this", "hat", "was", "too",
"small", ",", "then", "it", "got", "used", "to", "me", ".", "they",
"gave", "me", "a", "tie", ",", "after", "long", "discussion",
".", "it", "seemed", "a", "pretty", "tie", "to", "me", ",", "but",
"i", "didn’t", "like", "it", ".", "when", "it", "came", "at",
"last", "i", "was", "too", "tired", "to", "send", "it", "back",
".", "but", "in", "the", "end", "it", "came", "in", "useful",
".", "it", "was", "blue", ",", "with", "kinds", "of", "little",
"stars", ".", "i", "didn’t", "feel", "well", ",", "but", "they",
"told", "me", "i", "was", "well", "enough", "."), middleFr_Expelled_1946 = c("the",
"expelled", "there", "were", "not", "many", "steps", ".", "i",
"had", "counted", "them", "a", "thousand", "times", ",", "both",
"going", "up", "and", "coming", "down", ",", "but", "the", "figure",
"has", "gone", "from", "my", "mind", ".", "i", "have", "never",
"known", "whether", "you", "should", "say", "one", "with", "your",
"every", "day", "several", "times", "a", "day", ",", "until",
"they", "sink", "forever", "in", "the", "mud", ".", "that’s",
"an", "order", ".")), class = "stylo.corpus", call = load.corpus.and.parse(files = "all",
corpus.dir = "x", markup.type = "plain", corpus.lang = "English.all",
splitting.rule = ("[ \t\n]+"), sampling = "no.sampling",
features = "w", ngram.size = 1, preserve.case = FALSE, encoding = "UTF-8"))
freq.list <- c("", "-", "—", ",", ";", ":", "!", "?", ".", "’", "\"",
"(", ")", "a", "about", "above", "across", "after", "again",
"against", "ah", "all", "almost", "along", "Already", "also",
"always", "am", "among", "an", "and", "another", "any", "anything",
"are", "as", "at", "away", "back", "be", "because", "been", "before",
"behind", "being", "best", "better", "between", "beyond", "both",
"but", "by", "came", "can", "can't", "can’t", "cannot", "come",
"comes", "could", "did", "didn’t", "different", "do", "does",
"doing", "don't", "don’t", "done", "down", "each", "either",
"else", "even", "ever", "every", "everything", "except", "far",
"few", "fifteen", "first", "five", "for", "forward", "four",
"from", "get", "go", "goes", "going", "got", "great", "had",
"half", "has", "have", "having", "he", "her", "here", "herself",
"him", "himself", "his", "how", "however", "hundred", "i", "i'll",
"i'm", "i’ll", "if", "in", "indeed", "instead", "into", "is",
"it", "it's", "it’s", "its", "itself", "just", "last", "late",
"least", "left", "less", "let", "like", "little", "long", "made",
"make", "many", "may", "me", "merely", "might", "mine", "more",
"most", "moved", "much", "must", "my", "myself", "near", "neither",
"never", "next", "no", "none", "nor", "not", "nothing", "now",
"of", "off", "often", "oh", "on", "once", "one", "only", "or",
"other", "others", "otherwise", "our", "out", "over", "own",
"perhaps", "place", "quite", "rather", "really", "right", "said",
"same", "say", "second", "shall", "she", "should", "since", "six",
"small", "so", "some", "someone", "something", "sometimes", "somewhere",
"soon", "still", "such", "ten", "than", "that", "that's", "that’s",
"the", "their", "them", "themselves", "then", "there", "therefore",
"these", "they", "thing", "things", "third", "this", "those",
"though", "three", "through", "thus", "till", "time", "times",
"to", "together", "too", "towards", "two", "under", "unless",
"until", "up", "upon", "us", "very", "was", "way", "we", "well",
"went", "were", "what", "whatever", "when", "where", "whether",
"which", "while", "who", "whom", "whose", "why", "will", "with",
"within", "without", "won't", "would", "yes", "yet", "you", "your",
"yourself")
You can do:
b <- word.frequencies[18,1:263, drop = F]
dim(b)
# [1] 1 263

Creating a word cloud in R [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed last year.
Improve this question
I'm trying to create a wordcloud from a large data set. I've already read the text in and cleaned it. I have tried using wordcloud with the data in a dataframe format as well as in a matrix format, but I get an error either way stating there is an error in UseMethod for TermDocumentMatrix applied to an object class "data.frame" or "matrix".
Below is a shortened version of dput I'm attempting to work with in this capacity:
> dput(billing.mat)
structure(c("", "newest", "managers", "are", "doing", "really", "well",
"responses", "to", "client", "questions", "have", "been", "much",
"better", "than", "expected", "for", "the", "short", "time",
"they", "have", "been", "in", "their", "position", "", "trainee",
"mentioned", "they", "didnt", "feel", "like", "they", "were",
"getting", "enough", "supporthelp", "with", "the", "specific",
"things", "their", "team", "does", "the", "team", "puts", "properties"
), .Dim = c(50L,
1L), .Dimnames = list(NULL, "billing"))
>
Not sure exactly what you are doing but you can create a word cloud from a vector like this.
library(wordcloud)
library(tm)
data <- structure(c("", "newest", "managers", "are", "doing", "really", "well",
"responses", "to", "client", "questions", "have", "been", "much",
"better", "than", "expected", "for", "the", "short", "time",
"they", "have", "been", "in", "their", "position", "", "trainee",
"mentioned", "they", "didnt", "feel", "like", "they", "were",
"getting", "enough", "supporthelp", "with", "the", "specific",
"things", "their", "team", "does", "the", "team", "puts", "properties"
), .Dim = c(50L,
1L), .Dimnames = list(NULL, "billing"))
wordcloud(data)

how to break the key value and stored in two different variable to use them as parameter(stored_procedure) in ms SQL server in r and shiny

library(shinyjs)
library(plotly)
library(shinydashboard)
library(shinycssloaders)
library(shiny)
library(dplyr)
library(DT)
library(tidyr)
library(shinycustomloader)
library(tibble)
library(datapasta)
COL = c("#293a80","#39375b","#6915cf","#4b8e8d","#d55252","#293462","#940a37","#f54291","#f0134d","#b22222","#3c4245","#5d1451","#3c3d47")
ui<- fluidPage(
fluidRow(column(width=12,
withLoader(plotlyOutput("plott1"),type = "html",loader = "loader4"))),
fluidRow(column(width=12,
withLoader(plotlyOutput("plott2"),type = "html",loader = "loader1"))),
fluidRow(column(width=12,
withLoader(plotlyOutput("plott3")))),
fluidRow(column(width=12,
withLoader(plotlyOutput("plott4")))),
fluidRow(column(width=12,
withLoader(plotlyOutput("plott5")))),
fluidRow(verbatimTextOutput("plott6"))
)
server<- function(input,output)
{
output$plott1 <- renderPlotly({
sp1<-tibble::tribble(
~DID, ~DistrictName, ~BlockName, ~CenterName, ~TotRaj, ~TotOtherState, ~StateCode,
76, "state", "null", "null", 7656454, 5645345, "null"
)
ds <- data.frame(labels = c("Rajasthan","Other_State"),
values = c(sp1$TotRaj,sp1$TotOtherState)
)
plot_ly(ds, labels = ~labels, values = ~values,type = 'pie',source ='listenhere1',
textposition = 'inside',
textinfo = 'label+percent',
insidetextfont = list(color = '#FFFFFF'),
marker = list(colors = c('#5d1451','#745c97'),
line = list(color =colors , width = 1)),showlegend = FALSE) %>%
layout(
xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))
})
output$plott2 <- renderPlotly({
s <- event_data("plotly_click", source = "listenhere1")
req(!is.null(s))
if(s$pointNumber == 0){
sp2<-tibble::tribble(
~DID, ~DistrictName, ~BlockName, ~CenterName, ~TotRaj, ~TotOtherState, ~StateCode,
101, "a", "null", "null", 564534, 564534, "null",
201, "b", "null", "null", 675645, 765645, "null",
301, "c", "null", "null", 765645, 786756, "null",
401, "d", "null", "null", 987656, 764534, "null",
501, "e", "null", "null", 675645, 543423, "null",
601, "f", "null", "null", 765434, 231234, "null",
701, "g", "null", "null", 564534, 763423, "null",
801, "h", "null", "null", 234565, 567876, "null",
901, "i", "null", "null", 985646, 876345, "null",
102, "j", "null", "null", 876754, 453675, "null",
202, "k", "null", "null", 876756, 876754, "null"
)
layout <- list(
font = list(size = 12),
title = " District-Wise",
xaxis = list(title = "district"),
yaxis = list(title = "records",automargin = TRUE)
)
p <- plot_ly(sp2, x = sp2$DistrictName, y = sp2$TotRaj, type = 'bar', name = '',source = 'link3',key = ~paste(sp2$DID, sep = ""),marker = list(color = '#baabda')) %>%
add_trace(y = sp2$TotOtherState, name = 'Other_State',marker = list(color = '#58508d')) %>%
layout(yaxis = list(title = ''), barmode = 'stack')
}
else {
sp2<-tibble::tribble(
~DID, ~DistrictName, ~BlockName, ~CenterName, ~TotRaj, ~TotOtherState, ~StateCode,
101, "a", "null", "null", 564534, 564534, "null",
201, "b", "null", "null", 675645, 765645, "null",
301, "c", "null", "null", 765645, 786756, "null",
401, "d", "null", "null", 987656, 764534, "null",
501, "e", "null", "null", 675645, 543423, "null",
601, "f", "null", "null", 765434, 231234, "null",
701, "g", "null", "null", 564534, 763423, "null",
801, "h", "null", "null", 234565, 567876, "null",
901, "i", "null", "null", 985646, 876345, "null",
102, "j", "null", "null", 876754, 453675, "null",
202, "k", "null", "null", 876756, 876754, "null"
)
tablename=rowSums(cbind(sp2$TotRaj,sp2$TotOtherState),na.rm=TRUE)
layout <- list(
font = list(size = 12),
title = " Other-State",
xaxis = list(title = "RECORDS"),
yaxis = list(title ="STATES" ,automargin = TRUE)
)
p <- plot_ly(sp2, colors = COL, marker = list(color = COL),source = 'linkhere',orientation='h',key = ~paste(sp2$DID, sep = "")) %>%
add_trace( x =sp2$TotOtherState,y = sp2$StateName,name = "states",type = 'bar') %>%
layout( font = layout$font, title = layout$title, xaxis = layout$xaxis, yaxis = layout$yaxis)
}
})
output$plott3 <- renderPlotly({
d<-event_data('plotly_click',source = 'link3')
if(is.null(d)==F){
sp3<-data.frame(stringsAsFactors=FALSE,
DID = c(101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101),
DistrictName = c("a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a"),
BlockName = c("aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg", "hhh",
"iii", "jjj", "kkk"),
CenterName = c("null", "null", "null", "null", "null", "null", "null",
"null", "null", "null", "null"),
TotRaj = c(564534, 675645, 765645, 987656, 675645, 765434, 564534,
234565, 985646, 876754, 876756),
TotOtherState = c(564534, 765645, 786756, 764534, 543423, 231234, 763423,
567876, 876345, 453675, 876754),
StateCode = c("null", "null", "null", "null", "null", "null", "null",
"null", "null", "null", "null"),
CID = c("c01", "c02", "c03", "c04", "c05", "c06", "c07", "c08",
"c09", "c10", "c11")
)
p <- plot_ly(sp3, x = sp3$BlockName, y = sp3$TotRaj, type = 'bar', name = '',key = ~paste(sp3$DID,sep = ",",sp3$CID), source = 'link1',marker = list(color = '#537ec5')) %>%
add_trace(y = sp3$TotOtherState, name = 'other-state',marker = list(color = '#57007e')) %>%
layout(yaxis = list(title = 'sonography block_level'),xaxis = list(title = 'Block name'), barmode = 'group',title='')}
else{
return(NULL)
}
})
output$plott4 <- renderPlotly({
d<-event_data('plotly_click',source = 'link1')
if(is.null(d)==F){
sp4<-data.frame(stringsAsFactors=FALSE,
DID = c(101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101),
DistrictName = c("a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a"),
BlockName = c("aaa", "aaa", "aaa", "aaa", "aaa", "aaa", "aaa", "aaa",
"aaa", "aaa", "aaa"),
CenterName = c("abc", "bac", "dac", "efc", "ghc", "hic", "jkl", "mnl",
"lkj", "ghj", "kjh"),
TotRaj = c(2345, 2343, 6754, 7656, 8767, 6756, 4534, 5678, 6756,
5434, 9876),
TotOtherState = c(4532, 2345, 3456, 4567, 9845, 9876, 6756, 5645, 4534,
5645, 7865),
StateCode = c("null", "null", "null", "null", "null", "null", "null",
"null", "null", "null", "null"),
CID = c("c01", "c02", "c03", "c04", "c05", "c06", "c07", "c08",
"c09", "c10", "c11")
)
p <- plot_ly(sp4, x = sp4$TotRaj, y =sp4$CenterName , type = 'bar', name = 'rajasthan',key = ~paste(sp4$CID, sep = ""),source = "hey",
marker = list(color = '#1a3e59',
line = list(color = 'rgba(246, 78, 139, 1.0)'))) %>%
add_trace(x = sp4$TotFormFOtherState, name = 'other-state',
marker = list(color = '#baabda',
line = list(color = 'rgba(58, 71, 80, 1.0)'))) %>%
layout(barmode = 'stack',
xaxis = list(title = "Centre Data"),
yaxis = list(title ="Centre Name"))}
else{return(NULL)}
})
output$plott5 <- renderPlotly({
s <- event_data("plotly_click", source = "linkhere")
req(!is.null(s))
sp5<-tibble::tribble(
~DID, ~DistrictName, ~BlockName, ~CenterName, ~TotRaj, ~TotOtherState, ~StateCode, ~CID, ~StateName,
"null", "null", "null", "nul", "nul", 4532, 1, "null", "alpha",
"null", "null", "null", "nul", "nul", 2345, 2, "null", "beta",
"null", "null", "null", "nul", "nul", 3456, 3, "null", "gama",
"null", "null", "null", "nul", "nul", 4567, 4, "null", "theta",
"null", "null", "null", "nul", "nul", 9845, 5, "null", "abn",
"null", "null", "null", "nul", "nul", 9876, 6, "null", "mnb",
"null", "null", "null", "nul", "nul", 6756, 7, "null", "vbg",
"null", "null", "null", "nul", "nul", 5645, 8, "null", "hjg",
"null", "null", "null", "nul", "nul", 4534, 9, "null", "klj",
"null", "null", "null", "nul", "nul", 5645, 10, "null", "ghj",
"null", "null", "null", "nul", "nul", 7865, 11, "null", "jhg"
)
layout <- list(
font = list(size = 12),
title = " District-Wise",
xaxis = list(title = "district"),
yaxis = list(title = "records",automargin = TRUE)
)
p <- plot_ly(sp5, x = sp5$StateName, y = sp5$TotOtherState, type = 'bar', name = '',source = 'link3',key = ~paste(sp5$DID, sep = ""),marker = list(color = COL))
})
output$plott6<-renderPrint({
s<-event_data("plotly_click",source = "link1")
if(length(s)==0)
{
"CLICK ON BARCHART TO PRINT THE VALUES!"
}
else{
as.list(s)
}
})
}
runApp(list(ui = ui, server = server), launch.browser = TRUE)
screenshots to make it understand better...
enter image description here
enter image description here
i am using the stored procedure from ms SQL server for this purpose but created it the simplest way possible to make it run on other's machines. as shown in the images, how to break the key value into two values and store them in two different variables.how to split and store them.
Here is a minimal example on how to filter your dataset based on plotly_click-events and pass the resulting variables as parameters to a SQL query:
library(shiny)
library(plotly)
library(datasets)
ui <- fluidPage(
plotlyOutput("myPlot"),
tableOutput("myQueryResult"),
textOutput("myExampleQuery")
)
keyedIris <- iris
# create unique row id
keyedIris$myKey <- 1:nrow(keyedIris)
server <- function(input, output, session) {
output$myPlot <- renderPlotly(plot_ly(keyedIris, x = ~Sepal.Length, y = ~Sepal.Width, color = ~Species, type = "scatter", mode = "markers", source = "mySource", key = ~myKey))
filteredIris <- reactive({
myPlotEvents <- event_data(event = "plotly_click", source = "mySource")
keyedIris[keyedIris$myKey %in% myPlotEvents$key,]
})
output$myQueryResult <- renderTable({
filteredIris()
})
output$myExampleQuery <- renderText({
sprintf("SELECT * FROM iris WHERE Species IN (%s) AND Petal.Length IN (%s) AND Petal.Width IN (%s)", filteredIris()$Species, filteredIris()$Petal.Length, filteredIris()$Petal.Width)
})
}
shinyApp(ui, server)

How to use the predict function with categorical interaction terms in R

I am trying to use predict() to find prediction values for a linear regression pertaining to kick offs in football. My model is:
fit8 <- lm(endyl ~ gdate + kt + rt+ ylr + gdate*rt + kt*ylr + gdate*kt
+ gdate*kt*ylr, data = returned_kicks)
endyl and ylr are numerical, but gdate, kt, and rt, are all categorical with 4, 32, and 32 levels respectively. As you can see there are 4 interaction terms and they use the categorical predictors. My attempt at predicting looks like this:
newdata1 <- with(returned_kicks, data.frame(gdate = factor('Nov', levels = c('Sept', 'Oct', 'Nov', 'Dec')),
kt = factor("ATL", levels =c("ARI", "ATL", "BAL", "BUF", "CAR", "CHI", "CIN", "CLE", "DAL", "DEN", "DET", "GB", "HOU", "IND", "JAX",
"KC", "LA", "MIA","MIN", "NE", "NO", "NYG", "NYJ", "OAK", "PHI","PIT", "SD", "SEA", "SF", "TB", "TEN", "WAS")),
rt = factor("BUF", levels =c("ARI", "ATL", "BAL", "BUF", "CAR", "CHI", "CIN", "CLE", "DAL", "DEN", "DET", "GB", "HOU", "IND", "JAX",
"KC", "LA", "MIA","MIN", "NE", "NO", "NYG", "NYJ", "OAK", "PHI","PIT", "SD", "SEA", "SF", "TB", "TEN", "WAS")), ylr = -5))
newdata1
predict.lm(fit8, newdata = newdata1, type = "response")
I have seen some places say including the levels like that helps with categorical predictors, but it doesn't seem to be accounting for the interaction terms. Am I doing something wrong in the predict function or am I setting up the data.frame wrong? Any suggestions on how to fix the error are appreciated, thank you.

Resources