Reputation: 265
I have rows of data with duplicate lat/longs and I want to include a label that has all of the grouped column data.
# Make sample dataframe
long <- c(147.5, 147.5, 147.5, 147, 147)
lat <- c(-36.5, -36.5, -36.5, -36, -36)
label <- c(1, 1, 2, 1, 2)
markers <- data.frame(lat,long,label)
# Combine labels based on lat long
markers <- markers %>%
group_by(lat, long) %>%
summarize(concat_label = toString(label))
# Markers with all of the labels
leaflet() %>%
addTiles() %>%
addMarkers(lng=markers$long, lat= markers$lat,
popup= markers$concat_label
)
Is there a version of toString that uses a line break instead of a comma? I tried to use paste and paste0 but wasn't able to get it to work.
Upvotes: 6
Views: 6633
Reputation: 1203
This is essentially @Erin's answer with one change. I think the task can be accomplished with paste0
which offers an advantage over various other possible methods that involve use of some flavor of sep= "<br>"
. With paste0
one has more control over where <br>
tags are placed. Here two items are joined and then broken so that numbers are named in the popup. For additional styling use HTML tags in the paste0
call.
# Make sample dataframe
long <- c(147.5, 147.5, 147.5, 147, 147)
lat <- c(-36.5, -36.5, -36.5, -36, -36)
label <- c(1, 1, 2, 1, 2)
markers <- data.frame(lat,long,label)
# Paste0 Method
# This has the advantage of controlling where the breaks go.
markers$label <- paste0("Longitude: ", long,"<br>",
"Latitude: ",lat, "<br>",
"Label: ",label)
# Markers with all of the labels
leaflet() %>%
addTiles() %>%
addMarkers(lng=markers$long, lat= markers$lat,
popup= markers$label)
Upvotes: 1
Reputation: 265
# Make sample dataframe
long <- c(147.5, 147.5, 147.5, 147, 147)
lat <- c(-36.5, -36.5, -36.5, -36, -36)
label <- c(1, 1, 2, 1, 2)
markers <- data.frame(lat,long,label)
# Aggregate method
markers <- aggregate(label ~ lat + long, markers, paste, collapse = "<br/>")
# Markers with all of the labels
leaflet() %>%
addTiles() %>%
addMarkers(lng=markers$long, lat= markers$lat,
popup= markers$label
)
This question had the answer: Collapse / concatenate / aggregate a column to a single comma separated string within each group
Upvotes: 3
Reputation: 1228
Your label variable can be an HTML string, so you can make the labels stack on each other with a <br/>
tag. For example:
library(leaflet)
long <- c(147.768, 147.768, 147.768,147.768, 147.768, 147.768)
lat <- c(-36.852, -36.852, -36.852,-36.852, -36.852, -36.852)
label <- paste(sep = "<br/>",'long label1', 'long label2', 'long label3','long label4', 'long label5', 'long label6')
markers <- data.frame(lat,long,label)
leaflet() %>%
addTiles() %>%
addMarkers(lng=markers$long, lat= markers$lat,
popup=markers$label,
)
You can also feed variables into the labels using the same approach - concatenating line-by-line.
Upvotes: 4