How to add padding between regular button and actionButton in shinyApp? - html

I have 2 individual (differently styled) buttons in my shiny App that unfortunately have no vertical padding between them. One of them is a simple HTML button while the other is a shiny actionButton.
I have tried using tags$style but don't think I am using it correctly. My code for the relevant parts are
HTML('<button data-toggle="collapse" data-target="#addtools">Additional tools</button>'),
tags$div(id = 'addtools', class="collapse",
checkboxInput("cluster", "Cluster customers", value = TRUE),
checkboxInput("circle", "Add circles", value = FALSE),
conditionalPanel("input.circle",
selectInput("sizes", "Radius:",
c("5 miles" = "5",
"10 miles" = "10",
"20 miles" = "20"))
)
),
actionButton("runfilters", label = "Apply filters")
The entire UI part of this file is:
tabPanel("Map",
div(class="outer",
tags$head(
includeCSS("styles.css"),
includeScript("gomap.js")
),
leafletOutput(outputId = "map", width = "100%", height = "100%"),
absolutePanel(id = "controls", class = "panel panel-default", fixed = TRUE,
draggable = TRUE, top = 60, left = "auto", right = 20, bottom = "auto",
width = 330, height = "auto",
h2("Select your filters:"),
selectInput("level",
"Detail level:",
c("Customer level", "County level"),
selected = "County level"),
selectInput("mapstates","States:", c("All states"="",
structure(state.abb, names=state.name),
"Washington, DC"="DC"),
multiple = TRUE
),
conditionalPanel("input.mapstates",
selectInput("mapcounties", "Counties", c("All counties"=""),
multiple = TRUE
)
),
radioButtons("retailcorrection","Customer ownership:",
c("Private",
"Public"),
selected = "Private",
inline = TRUE),
conditionalPanel("input.level == 'Customer level'",
selectInput("var",
label = "Customer type:",
choices = c("ALL",
"ESSENTIAL",
"NON-ESSENTIAL"),
selected = "ALL"
),
radioButtons("custoporoh","Widget Category:",
c("Widget A",
"Widget B"),
selected = "Widget A",
inline = TRUE),
conditionalPanel("input.custoporoh == 'Widget A'",
numericInput("oprange",
label = "Minimum average monthly Widget A ordering (in dosage units):",
min = 0, max = 1000000, value = 0
),
numericInput("opprange",
label = "Minimum average monthly Widget A ordering as a percentage of total ordering:",
min = -1, max = 1, value = -1
)
),
conditionalPanel("input.custoporoh == 'Widget B'",
numericInput("ohrange","Minimum average monthly Widget B ordering (in dosage units):",
min = 0, max = 1000000, value = 0
),
numericInput("ohprange",
label = "Minimum average monthly Widget B ordering as a percentage of total ordering:",
min = -1, max = 1, value = -1
)
),
HTML('<button data-toggle="collapse" data-target="#addtools">Additional tools</button>'),
tags$div(id = 'addtools', class="collapse",
checkboxInput("cluster", "Cluster customers", value = TRUE),
checkboxInput("circle", "Add circles", value = FALSE),
conditionalPanel("input.circle",
selectInput("sizes", "Radius:",
c("5 miles" = "5",
"10 miles" = "10",
"20 miles" = "20"))
)
)
),
conditionalPanel("input.level == 'County level'",
selectInput("countyvar",
label = "Customer type:",
choices = c("ALL",
"ESSENTIAL"),
selected = "ALL"
),
selectInput("year", "Year:",
choices = c("2006","2007","2008","2009","2010","2011", "2012",
"2013","2014","2015","2016","2017","2018", "All years" = "2019"),
selected = "2019"
),
radioButtons("oporoh","Widget Category:",
c("Widget A",
"Widget B"),
selected = "Widget A",
inline = TRUE),
conditionalPanel("input.oporoh == 'Widget A'",
numericInput("opppcrange",
label = HTML("Minimum Widget A units per adult per month:"),
min = 0, max = 160, value = 0
),
numericInput("opcrange",
label = "Minimum average monthly Widget A ordering (in dosage units):",
min = 0, max = 10000000, value = 0
),
numericInput("oppcrange",
label = "Minimum average monthly Widget A ordering as a percentage of total ordering:",
min = -1, max = 1, value = -1
)
),
conditionalPanel("input.oporoh == 'Widget B'",
numericInput("ohppcrange",
label = "Minimum Widget B units per adult per month:",
min = 0, max = 160, value = 0
),
numericInput("ohcrange","Minimum average monthly Widget B ordering (in dosage units):",
min = 0, max = 10000000, value = 0
),
numericInput("ohpcrange",
label = "Minimum average monthly Widget B ordering as a percentage of total ordering:",
min = -1, max = 1, value = -1
)
)
),
actionButton("runfilters", label = "Apply filters")
)
)
)
I have tried to implement:
HTML('<button data-toggle="collapse" data-target="#addtools">Additional tools</button>'),
tags$div(id = 'addtools', class="collapse", tags$style = "padding=10px"
but that doesn't seem to be working. Any help would be appreciated.

Related

JSON to Excel PowerQuery import - how to get a row per nested field

I'm looking to use the Excel Power Query to import some json that looks like the following (but much bigger, more fields etc.):
example-records.json
{
"records": {
"record_id_1": {
"file_no": "5792C",
"loads": {
"load_id_1": {
"docket_no": "3116115"
},
"load_id_2": {
"docket_no": "3116118"
},
"load_id_3": {
"docket_no": "3208776"
}
}
},
"record_id_2": {
"file_no": "5645C",
"loads": {
"load_id_4": {
"docket_no": "2000527155"
},
"load_id_5": {
"docket_no": "2000527156"
},
"load_id_6": {
"docket_no": "2000527146"
}
}
}
}
}
I want to get a table like the following at the load_id / docket level. A row per load_id
What I've tried
Clicking buttons in power query UI I get the following.
The problem is I can't include a file_no column and this doesn't work when there are lots of load ids.
let
Source = Json.Document(File.Contents("H:\Software\Site Apps\example-records.json")),
records = Source[records],
#"Converted to Table" = Record.ToTable(records),
#"Expanded Value" = Table.ExpandRecordColumn(#"Converted to Table", "Value", {"file_no", "loads"}, {"Value.file_no", "Value.loads"}),
#"Removed Columns" = Table.RemoveColumns(#"Expanded Value",{"Value.file_no"}),
#"Expanded Value.loads" = Table.ExpandRecordColumn(#"Removed Columns", "Value.loads", {"load_id_1", "load_id_2", "load_id_3", "load_id_4", "load_id_5", "load_id_6"}, {"Value.loads.load_id_1", "Value.loads.load_id_2", "Value.loads.load_id_3", "Value.loads.load_id_4", "Value.loads.load_id_5", "Value.loads.load_id_6"}),
#"Unpivoted Columns" = Table.UnpivotOtherColumns(#"Expanded Value.loads", {"Name"}, "Attribute", "Value"),
#"Expanded Value1" = Table.ExpandRecordColumn(#"Unpivoted Columns", "Value", {"docket_no"}, {"Value.docket_no"})
in
#"Expanded Value1"
You can use
let Source = JSON(Json.Document(File.Contents("c:\temp\example.json"))),
#"Removed Other Columns" = Table.SelectColumns(Source,{"Name.1", "Name.3", "Value"}),
#"Added Custom" = Table.AddColumn(#"Removed Other Columns", "Custom", each if [Name.3]=null then [Value] else null),
#"Filled Down" = Table.FillDown(#"Added Custom",{"Custom"}),
#"Filtered Rows" = Table.SelectRows(#"Filled Down", each ([Name.3] <> null))
in #"Filtered Rows"
based on this function I named JSON which comes from Imke https://www.thebiccountant.com/2018/06/17/automatically-expand-all-fields-from-a-json-document-in-power-bi-and-power-query/ which is reproduced below
let
func = (JSON) =>
let
Source = JSON,
ParseJSON = try Json.Document(Source) otherwise Source,
TransformForTable =
if Value.Is(ParseJSON, type record) then
Record.ToTable(ParseJSON)
else
#table(
{"Name", "Value"},
List.Zip({List.Repeat({0}, List.Count(ParseJSON)), ParseJSON})
),
AddSort = Table.Buffer(Table.AddColumn(TransformForTable, "Sort", each 0)),
LG = List.Skip(
List.Generate(
() => [Next = AddSort, Counter = 1, AddIndex = #table({"Sort"}, {{""}})],
each [AddIndex]{0}[Sort] <> "End",
each [
AddIndex = Table.AddIndexColumn([Next], "Index", 0, 1),
MergeSort = Table.CombineColumns(
Table.TransformColumnTypes(
AddIndex,
{{"Sort", type text}, {"Index", type text}},
"en-GB"
),
{"Sort", "Index"},
Combiner.CombineTextByDelimiter(".", QuoteStyle.None),
"Sort"
),
PJson = Table.TransformColumns(
MergeSort,
{{"Value", each try Json.Document(_) otherwise _}}
),
AddType = Table.AddColumn(
PJson,
"Type",
each
if Value.Is([Value], type record) then
"Record"
else if Value.Is([Value], type list) then
"List"
else if Value.Is([Value], type table) then
"Table"
else
"other"
),
AddStatus = Table.AddColumn(
AddType,
"Status",
each if [Type] = "other" then "Finished" else "Unfinished"
),
Finished = Table.SelectRows(AddStatus, each ([Status] = "Finished")),
Unfinished = Table.SelectRows(AddStatus, each ([Status] = "Unfinished")),
AddNext = Table.AddColumn(
Unfinished,
"Next",
each if [Type] = "Record" then {[Value]} else [Value]
),
RemoveCols = Table.RemoveColumns(AddNext, {"Value", "Type", "Status"}),
ExpandNext = Table.ExpandListColumn(RemoveCols, "Next"),
AddIndex2 = Table.AddIndexColumn(ExpandNext, "Index", 0, 1),
MergeSort2 = Table.CombineColumns(
Table.TransformColumnTypes(
AddIndex2,
{{"Sort", type text}, {"Index", type text}},
"en-GB"
),
{"Sort", "Index"},
Combiner.CombineTextByDelimiter(".", QuoteStyle.None),
"Sort"
),
TransformRecord = Table.TransformColumns(
MergeSort2,
{
{
"Next",
each try
Record.ToTable(_)
otherwise
try
if Value.Is(Text.From(_), type text) then
#table({"Value"}, {{_}})
else
_
otherwise
_
}
}
),
FilterOutNulls = Table.SelectRows(TransformRecord, each [Next] <> null),
Next =
if Table.IsEmpty(FilterOutNulls) then
#table({"Sort"}, {{"End"}})
else if Value.Is(FilterOutNulls[Next]{0}, type table) = true then
Table.ExpandTableColumn(
FilterOutNulls,
"Next",
{"Name", "Value"},
{"Name." & Text.From([Counter]), "Value"}
)
else
Table.RenameColumns(FilterOutNulls, {{"Next", "Value"}}),
Counter = [Counter] + 1
],
each Table.AddColumn([Finished], "Level", (x) => _[Counter] - 2)
)
),
Check = LG{2},
Combine = Table.Combine(LG),
Clean = Table.RemoveColumns(Combine, {"Status", "Type"}),
Trim = Table.TransformColumns(Clean, {{"Sort", each Text.Trim(_, "."), type text}}),
// Dynamic Padding for the sort-column so that it sorts by number in text strings
SelectSort = Table.SelectColumns(Trim, {"Sort"}),
SplitSort = Table.AddColumn(
SelectSort,
"Custom",
each List.Transform(try Text.Split([Sort], ".") otherwise {}, Number.From)
),
ToTable = Table.AddColumn(
SplitSort,
"Splitted",
each Table.AddIndexColumn(Table.FromColumns({[Custom]}), "Pos", 1, 1)
),
ExpandTable = Table.ExpandTableColumn(ToTable, "Splitted", {"Column1", "Pos"}),
GroupPos = Table.Group(
ExpandTable,
{"Pos"},
{{"All", each _, type table}, {"Max", each List.Max([Column1]), type text}}
),
Digits = Table.AddColumn(GroupPos, "Digits", each Text.Length(Text.From([Max]))),
FilteredDigits = List.Buffer(Table.SelectRows(Digits, each ([Digits] <> null))[Digits]),
SortNew = Table.AddColumn(
Trim,
"SortBy",
each Text.Combine(
List.Transform(
List.Zip({Text.Split([Sort], "."), List.Positions(Text.Split([Sort], "."))}),
each Text.PadStart(_{0}, FilteredDigits{_{1}}, "0")
),
"."
)
),
FilterNotNull = Table.SelectRows(SortNew, each ([Value] <> null)),
Reorder = Table.ReorderColumns(
FilterNotNull,
{"Value", "Level", "Sort", "SortBy"}
& List.Difference(
Table.ColumnNames(FilterNotNull),
{"Value", "Level", "Sort", "SortBy"}
)
),
Dots = Table.AddColumn(
#"Reorder",
"Dots",
each List.Select(Table.ColumnNames(#"Reorder"), (l) => Text.StartsWith(l, "Name"))
),
// This sort is just to view in the query editor. When loaded to the data model it will not be kept. Use "Sort by column" in the data model instead.
Sort = Table.Sort(Dots, {{"SortBy", Order.Ascending}})
in
Sort,
documentation = [
Documentation.Name = " Table.JsonExpandAll ",
Documentation.Description
= " Dynamically expands the <Json> Record and returns values in one column and additional columns to navigate. ",
Documentation.LongDescription
= " Dynamically expands the <Json> Record and returns values in one column and additional columns to navigate. Input can be JSON in binary format or the already parsed JSON. ",
Documentation.Category = " Table ",
Documentation.Version = " 1.2: Added column [Dots] (22/02/2019)",
Documentation.Author = " Imke Feldmann: www.TheBIccountant.com . ",
Documentation.Examples = {[Description = " ", Code = " ", Result = " "]}
]
in
Value.ReplaceType(func, Value.ReplaceMetadata(Value.Type(func), documentation))
Managed to use an added custom column, the action that enables the expansion to one load id per row.
#"Added Custom" = Table.AddColumn(#"Expanded Value", "Custom", each Record.ToTable([Value.loads]))
let
Source = Json.Document(File.Contents("H:\Software\Site Apps\example-records.json")),
records = Source[records],
#"Converted to Table" = Record.ToTable(records),
#"Expanded Value" = Table.ExpandRecordColumn(#"Converted to Table", "Value", {"file_no", "loads"}, {"Value.file_no", "Value.loads"}),
#"Added Custom" = Table.AddColumn(#"Expanded Value", "Custom", each Record.ToTable([Value.loads])),
#"Removed Columns" = Table.RemoveColumns(#"Added Custom",{"Value.loads"}),
#"Expanded Custom" = Table.ExpandTableColumn(#"Removed Columns", "Custom", {"Name", "Value"}, {"Custom.Name", "Custom.Value"}),
#"Expanded Custom.Value" = Table.ExpandRecordColumn(#"Expanded Custom", "Custom.Value", {"docket_no"}, {"Custom.Value.docket_no"}),
#"Renamed Columns" = Table.RenameColumns(#"Expanded Custom.Value",{{"Name", "record_id"}, {"Value.file_no", "file_no"}, {"Custom.Name", "load_id"}, {"Custom.Value.docket_no", "docket_no"}})
in
#"Renamed Columns"

Implement function call (grouped running totals) in query

I have a function called fxGroupedRunningTotal (fxGRT) and a query (Totals). I want to call fxGRT within Totals, so that I get a column that shows the grouped running totals. I have only managed to test the fxGRT by importing the Totals query.
Query that uses Totals and calls fxGRT (built for testing the function):
let
Source = Totals,
BufferedValues = List.Buffer(Source[PD]),
BufferedMaterials = List.Buffer(Source[Material]),
RT = Table.FromColumns(
{
Source[Material], Source[Date], Source[PD],
fxGroupedRunningTotal(BufferedValues, BufferedMaterials)
},
{
"Material",
"Date",
"PD",
"Running Total"
})
in
RT
fxGroupedRunningTotals:
(values as list, grouping as list) as list =>
let
GRTList = List.Generate
(
()=> [ GRT = values{0}, i = 0 ],
each [i] < List.Count(values),
each try if grouping{[i]} = grouping{[i] + 1}
then [GRT = [GRT] + values {[i] + 1}, i = [i] + 1]
else [GRT = values{[i] + 1}, i = [i] + 1]
otherwise [i = [i] + 1]
,
each [GRT]
)
in
GRTList
Totals:
let
Källa = Table.NestedJoin(Cohv,{"Prod MDate"},Resb,{"Del Mdate"},"Resb",JoinKind.FullOuter),
#"Expanderad Resb" = Table.ExpandTableColumn(Källa, "Resb", {"Del Material", "Del Date", "Del Qty", "Del Mdate"}, {"Del Material", "Del Date", "Del Qty", "Del Mdate"}),
#"PD Date" = Table.AddColumn(#"Expanderad Resb", "PD Date", each if [Prod Date] = null then [Del Date] else [Prod Date]),
#"PD Material" = Table.AddColumn(#"PD Date", "PD Material", each if [Material Number] = null then [Del Material] else [Material Number]),
#"PD Mdate" = Table.AddColumn(#"PD Material", "PD Mdate", each [PD Material] & "." & Date.ToText([PD Date])),
#"Borttagna kolumner" = Table.RemoveColumns(#"PD Mdate",{"Prod Date", "Prod MDate", "Del Date", "Del Mdate"}),
#"Ändrad typ1" = Table.TransformColumnTypes(#"Borttagna kolumner",{{"PD Date", type date}}),
#"Ihopslagna frågor" = Table.NestedJoin(#"Ändrad typ1",{"PD Material"},Matmas,{"Material"},"Matmas",JoinKind.FullOuter),
#"Expanderad Matmas" = Table.ExpandTableColumn(#"Ihopslagna frågor", "Matmas", {"Material", "Material Description", "MRP Controller", "Safety stock", "Minimum Lot Size", "In Stock"}, {"Material", "Material Description", "MRP Controller", "Safety stock", "Minimum Lot Size", "In Stock"}),
#"Omdöpta kolumner" = Table.RenameColumns(#"Expanderad Matmas",{{"Material", "M Material"}}),
#"Lägg till egen" = Table.AddColumn(#"Omdöpta kolumner", "Material", each if [PD Material] = null then [M Material]else [PD Material]),
#"Borttagna kolumner1" = Table.RemoveColumns(#"Lägg till egen",{"Material Number", "Del Material", "PD Material", "M Material"}),
#"Lägg till egen1" = Table.AddColumn(#"Borttagna kolumner1", "Date", each if [PD Date] = null then DateTime.LocalNow() else [PD Date]),
#"Borttagna kolumner2" = Table.RemoveColumns(#"Lägg till egen1",{"PD Date"}),
#"Lägg till egen2" = Table.AddColumn(#"Borttagna kolumner2", "Date in stock", each if [Date] = DateTime.Date(DateTime.LocalNow()) then [In Stock] else null),
#"Borttagna kolumner3" = Table.RemoveColumns(#"Lägg till egen2",{"Date in stock"}),
#"Ändrad typ" = Table.TransformColumnTypes(#"Borttagna kolumner3",{{"Date", type date}}),
#"Ersatt värde" = Table.ReplaceValue(#"Ändrad typ",null,0,Replacer.ReplaceValue,{"Prod Qty"}),
#"Ersatt värde1" = Table.ReplaceValue(#"Ersatt värde",null,0,Replacer.ReplaceValue,{"Del Qty"}),
#"Ihopslagna frågor1" = Table.NestedJoin(#"Ersatt värde1",{"Date"},Dates,{"Date"},"Dates",JoinKind.RightOuter),
#"Expanderad Dates" = Table.ExpandTableColumn(#"Ihopslagna frågor1", "Dates", {"Current Date"}, {"Current Date"}),
#"Omdöpta kolumner1" = Table.RenameColumns(#"Expanderad Dates",{{"Date", "D Date"}}),
Date = Table.AddColumn(#"Omdöpta kolumner1", "Date", each if [D Date] is null then DateTime.Date(DateTime.LocalNow()) else [D Date]),
PD = Table.AddColumn(Date, "PD", each if [Current Date] = "Yes" then [In Stock]+[Prod Qty]-[Del Qty] else [Prod Qty]-[Del Qty])
in
PD
So how do I implement this function into a new column in my Totals? My attempts keep failing. Do I have to make a reference to Totals in order to make this work? It feels so wrong, since that would double the work load (?) with the data. I would like it to be as quick as possible.
You can reference the previous step as a table. Thus your query can be written
let
[...all your previous steps...]
PD = Table.AddColumn(Date, "PD", each if [Current Date] = "Yes" then [In Stock]+[Prod Qty]-[Del Qty] else [Prod Qty]-[Del Qty]),
RT =
Table.FromColumns(
List.Combine({Table.ToColumns(PD), {fxGroupedRunningTotals(PD[Material], PD[PD])}}),
List.Combine({Table.ColumnNames(PD), {"Running Total"}})
)
in
RT
This converts the table to a list of columns, adds on the new running total column (calling the function you've defined on specific columns of the table from the previous step PD), and then glues those columns back together with a similar method to preserve the column names and add a new one.

Custom Table Container with <br> is not working in datatable in R shiny

##This is a container that I am using in the data table, but br tag in the column name is not working.
I used escape = FALSE in the data table but still facing the same issue.
and \n is also not working. I want something like this column name = first name (in the next line) last name.
test <- function(group,n){
htmltools::withTags(th(colspan = n, group, class = "dt-center"))
}
myContainer <- htmltools::withTags(table(
class = '',style="width:100%",
thead(
tr(
th(rowspan = 2, ' '),
th(colspan = 1, 'group 1', class = "dt-center"),
th(colspan = 2, 'group 2', class = "dt-center"),
th(colspan = 2, 'group 3', class = "dt-center")
),
tr(
th("new \\\\n ID"),
lapply(c("SUBJID","SITE<br>ID","AG<br>E","SUBJID","RACE"), th)
)
)
))
Server <- function(input, output, session) {
adae<-read_sas("C:/Arinjay_Intern/Work/ADaM/adae.sas7bdat")
output$intTable<-renderDT({adae_df %>%
datatable(class= 'compact', extensions = 'Buttons', rownames = F, container = myContainer,escape = FALSE,
callback = JS(c("$('table.dataTable thead th').css('border-top', 'none');",
"$('table.dataTable.no-footer').css('border-top', 'none');"
)),
options = list(dom = 'tB', pageLength = 5,
ordering = FALSE, class= "compact",
columnDefs = list(list(className = "dt-center", targets = "_all")),
buttons = 'pdf'
),
caption = htmltools::tags$caption(
style = 'caption-side: bottom; text-align: left;',
htmltools::em(HTML('N = number of subjects in the specified population. <br>n=number of subjects in each category. % = 100*n/N.')))
) %>%
formatStyle(c("USUBJID","SUBJID","SITEID","AGE", "SEX","RACE"), backgroundColor = 'white')
})
}
UI <-navbarPage(
"DT Interactive Tables",
tabPanel(
"ADaM DataSets",
fluidPage(
checkboxGroupInput('group','Please select a group',c('FD_Cohort','MRD_Cohort')),
textInput('n',"any value",value=2),
DTOutput("intTable")
)
)
)
shinyApp(UI,Server)
Expected output:
Neither \n or <br>, work in xtable. So, you could define the rows explicitly as shown below:
row1 <- c(" USUB","SUBJ","SITE","AG","SEX", "RACE")
row2 <- c("JID","ID","ID","E"," ", "")
myContainer <- htmltools::withTags(table(
class = 'dt-center', style="width:100%",
thead(
tr(
th(colspan = 2, 'group 1', class = "dt-center"),
th(colspan = 2, 'group 2', class = "dt-center"),
th(colspan = 2, 'group 3', class = "dt-center")
),
tr( lapply( row1, th)
),
tr( lapply( row2, th)
)
)
))
or you can write something in css or js to handle it. The above code gives the following output on a dummy dataset:

How we can column header in renderTable not in renderDataTable in R shiny? I want to group of few columns in my renderTable?

I am trying in this way:
myContainer <- htmltools::withTags(table(
class = '',style="width:100%",
thead(
tr(
th(colspan = 2, 'Group 1', class = "dt-center"),
th(colspan = 2, 'Group 2', class = "dt-center")
),
tr(
lapply(names(data.frame(df)), th)
)
)
))
#UI:
library(shiny)
shinyUI <- fluidPage(
fluidRow(
htmlOutput("TextTable")
)
My rendertable in server:
output$TextTable <- renderTable({
varsub
}, width = "100%", include.colnames = TRUE,
sanitize.text.function = identity, spacing = 's',
container = myContainer,
columnDefs = list(list(className = "dt-center", targets = "_all"))
)
But this is not working, any help would be appreciated. Or please suggest any other way to do it.

Function for changing size of points in geom_point based on sum of presence absence data

I'm working with a species data in presence/absence format set where samples have been taken multiple times a day over a period of several days.
Here's a dummy version of the data:
dummy = structure(list(Sample = c("A1", "A1", "A1", "A2", "A2", "A2",
"B1", "B1", "B1", "B2", "B2", "B2"), Species = c("snuffles1",
"snuffles2", "snuffles3", "snuffles1", "snuffles2", "snuffles3",
"snuffles1", "snuffles2", "snuffles3", "snuffles1", "snuffles2",
"snuffles3"), Presence = c(1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1
), Day = c("A", "A", "A", "A", "A", "A", "B", "B", "B", "B",
"B", "B")), row.names = c(NA, -12L), class = c("tbl_df", "tbl",
"data.frame"))
ggplot(dummy[which(dummy$Presence>0),], aes(x = Day, y = Species, color = Species)) +
geom_point(alpha=0.5) +
geom_count(aes(size = sum(dummy$Presence)))
I would like to plot the data in ggplot where the size of each point is dependent on the sum of the number of observations within that group (i.e if on Day A, snuffles1 was observed 2 times, then the point should be size 2, whereas if on Day B, snuffles1 was observed once, the point would be size 1). I hope this makes sense? This counting presence/absence based on group is similar, but not quite what I need.
My guess is that I have to use some sort of function to count the number of observations for each species, depedent on which variable I'm considering, but I am not smart enough to think of how to do this.
Thanks for any and all advice.
Make an additional count by group. Then plot this data frame as an extra layer using geom_point
I am adding breaks to scale_size in order to show only the exiting sizes
library(tidyverse)
count_dum <- dummy %>% group_by(Day, Species) %>% summarise(count = sum(Presence))
ggplot(dummy[which(dummy$Presence > 0), ], aes(x = Day, y = Species, color = Species)) +
geom_point(data = count_dum, aes(size = count), alpha = 0.5) +
scale_size_continuous(breaks = unique(count_dum$count))