R GGally color edges by vertex membership
I am trying to create a list to color the edges of a graph depending on the grouping of the vertices they connect to. If an edge connects two members of the same group, the edge has their color. If the edge is between members of different groups, the edges should be grey. Here is my code:
mnet = rgraph(10, mode = "graph", tprob = 0.5)
rownames(mnet)<letters[1:10]
colnames(mnet)<letters[1:10]
net = network(mnet, directed = FALSE, ignore.eval = FALSE, names.eval = "strength")
phono<data.frame(letters=letters[1:10],phono=c("vowel", "consonant","consonant","consonant","vowel","consonant","consonant","consonant","vowel", "consonant"))
table(phono)
net %v% "phono" < as.character(phono$phono)
nnet<matrix(0, 10, 10)
for (i in 1:10){
for (j in 1:10){
nnet[i,j] = ifelse(phono$phono[phono$letters %in% rownames(mnet)[i]]==phono$phono[phono$letters %in% colnames(mnet)[j]],
as.character(phono$phono[phono$letters %in% rownames(mnet)[i]]),
"grey50")
}
}
ggnet2(net, color = "phono", palette = "Set2", label = "phono", edge.color = unlist(nnet[upper.tri(nnet)])[unlist(mnet[upper.tri(mnet)])>0])
I am unhappy with that double loop in the middle of my R code. Is there a better way to do what I am trying to do? This is piggybacking off my most previous question which more tried to understand why "outer" wasn't working.
Also, the code doesn't work in general, but let's do one problem at a time. even though
length(unlist(nnet[upper.tri(nnet)])[unlist(mnet[upper.tri(mnet)])>0])==length(net %e% "strength")
Thanks.
See also questions close to this topic

R  nested loop for list of SpatialLinesDataFrame intersected with SpatialPolygonsDataFrame objects
I have a series of steps I need to complete on a list of
SpatialLinesDataFrame
('lines' herein) objects based on their relationships with individual features within a multifeatureSpatialPolygonsDataFrame
('polygons') object. In short, each line list element originates inside a single polygon feature, and may or may not pass through one or more other polygon features. I want to update each line element to connect origin polygons to the first point of contact for each individual polygon intersected by the line element. So, each line element may become multiple new line features (n=number of intersected polygons).I would like to do this efficiently as my lines lists and polygon features are numerous. I have provided example data and STEPwise description of what I am trying to do below. I am new to R and not a programmer, so I don't know if any of what I propose is valid.
library(sp) library(rgdal) library(raster) ###example data prep START #example 'RDCO Regional Parks' data can be downloaded here: https://datardco.opendata.arcgis.com/datasets group_ids=1950175c56c24073bb5cef3900e19460 parks < readOGR("/path/to/example/data/RDCO_Regional_Parks/RDCO_Regional_Parks.shp") plot(parks) #subset watersheds for example parks_sub < parks[parks@data$Shapearea > 400000,] plot(parks_sub, col='green', axes = T) #create SpatialLines from scratch pts_line1 < cbind(c(308000, 333000), c(5522000, 5530000)) line1 < spLines(pts_line1, crs = crs(parks_sub)) plot(line1, axes=T, add=T) #origin polygon = polyl[[4]] = OBJECTID 181 pts_line2 < cbind(c(308000, 325000), c(5524000, 5537000)) line2 < spLines(pts_line2, crs = crs(parks_sub)) plot(line2, axes=T, add=T) #origin polygon = polyl[[8]] = OBJECTID 1838 linel < list() linel[[1]] < line1 linel[[2]] < line2 #convert to SpatialLinesDataFrame objects lineldf < lapply(1:length(linel), function(i) SpatialLinesDataFrame(linel[[i]], data.frame(id=rep(i, length(linel[[i]]))), match.ID = FALSE)) #match id field value with origin polygon lineldf[[1]]@data$id < 181 lineldf[[2]]@data$id < 1838 ###example data prep END #initiate nested for loop for (i in 1:length(lineldf)) { for (j in 1:length(parks_sub[j,])) { #STEP 1:for each line list feature (NB: with ID matching origin polygon ID) #identify whether it intersects with a polygon list feature if (tryCatch(!is.null(intersect(lineldf[[i]], parks_sub[j,])), error=function(e) return(FALSE)) == 'FALSE'){ next } #if 'FALSE', go on to check intersect with next polygon in list #if 'TRUE', go to STEP 2 #STEP 2: add intersected polygon OBJECTID value to SLDF new column in attribute table #i.e., deal with single intersected polygon at a time else { lineldf[[i]]@data["id.2"] = parks_sub[j,]@data$OBJECTID #STEP 3: erase portion of line overlapped by intersected SPDF line_erase < erase(lineldf[[i]],parks_sub[j,]) #STEP 4: erase line feature(s) that no longer intersect with the origin polygon #DO NOT KNOW HOW TO SELECT feature (i.e., line segment) within 'line_erase' object if (tryCatch(!is.null(intersect(line_erase[???], parks_sub[j,])), error=function(e) return(FALSE)) == 'FALSE'){ line_erase[???] < NULL} else { #STEP 5: erase line features that only intersect with origin polygon if (line_erase[???]@data$id.2 = parks_sub[j,]@data$OBJECTID){ line_erase[???] < NULL } else { #STEP 6: write valid line files to folder writeOGR(line_erase, dsn = paste0("path/to/save/folder", i, ".shp"), layer = "newline", driver = 'ESRI Shapefile', overwrite_layer = T) }}}}}

How to format ggplot geom_text with formula, getting unwanted "c(...)"
In my code below, I want to show the formula for a linear fit on my plot with geom_text, but I get unwanted "c" before the values of a and b, how do I prevent this?
p < ggplot(data=Algae, aes(x=a254, y=DOC))+ geom_point(color="blue",stat="identity") + geom_smooth(method="lm",se=FALSE,color="red",formula=y~x) model.lm < lm(DOC~a254, data=Algae) l < list(a=format(coef(model.lm)[1], digits=4), b=format(coef(model.lm)[2], digits=4), r2=format(summary(model.lm)$r.squared, digits=4), p=format(summary(model.lm)$coefficients[2,4], digits=4)) eq < substitute(italic(DOC) == a  b %*% italic(a254)~","~italic(R)^2~"="~r2~", "~italic(P)~"="~p, l) p1 < p + geom_text(aes(x =6, y = 0, label = as.character(as.expression(eq))), parse = TRUE) p1

Hyperparameter Optimization to Find Minimum of Function in R
I have a dataset of 48 months that compares Actual and Estimated values based on a function. The function relies on a rate, X. I am trying to minimize the sum errors (ActualEstimated) for the entire time period. I am able to get the optimized X with optimize in R. However, I want to be able to find the right X for particular time periods that would give me a smaller sum of errors for the entire time period. What is the best way to do this in R? Or what method would work best for me to do this?
Actual Accounts = Actual Observations Cancelled = lag(Estimated Accounts) * .05 Estimated Accounts = Actual_Account  Cancelled

Replace Recursion with Iteration
i try change this algotitm to iterative https://github.com/hellogcc/circuitfindingalgorithm I have a recursive function which I try convert to an iterative function but I am quite stuck. Can anyone help or point me in the right direction?
bool CircuitFinder<N>::circuit(int V) { bool F = false; Stack.push_back(V); Blocked[V  1] = true; for (int W : AK[V  1]) { if (W == S) { output(); F = true; } else if (W > S && !Blocked[W  1]) { F = circuit(W); } } if (F) { unblock(V); } else { for (int W : AK[V  1]) { auto IT = std::find(B[W  1].begin(), B[W  1].end(), V); if (IT == B[W  1].end()) { B[W  1].push_back(V); } } } Stack.pop_back(); return F; }

Plot.ly js scale graph only for a trace
I'm creating a Plot.ly graph in javascript. The graph has points (scatter) and a line.
In the graph is possible to add points and move the line. I want the graph to
autoscale
andautosize
when a new point is added, but I don't want it to "move" when the line is moved.Is there a way to set the
autoscale
andautosize
layout values only for the points trace? Or alternatively, to set them tofalse
before moving the line and totrue
after the line is moved? Thank you 
This Python plot labelling is throwing an error and it makes no sense as to why?
My code is:
import matplotlib.pyplot as plot xval = [0,1,2,3,4] yval = [0,1,4,9,16] plot.scatter(xval,yval) plot.xlabel("x values") plot.ylabel("y values") plot.show()`
and the error is:
TypeError: 'str' object is not callable
on line 5
Does anyone have any idea what is wrong with the label function call?
EDIT: After the below comments I realised the browser based system I'm using (Jupyter Notebook) doesn't run each code block separately, so I just reset the kernel.

GGally: How can I remove the density plots in ggpairs/ggscatmat, and add a heat aesthetic to the correlation section?
I'm starting to get to grips with the
GGally
package and I'm a bit overwhelmed with the options. What I'd like is to sort of combineggpairs()
together with the heat aesthetic you get fromggcorr()
, and to replace the density plots with the relevant variable names.library(tidyverse); library(GGally) ggpairs(mpg[,c("displ","year","cyl","cty","hwy")])
with
ggcorr(mpg[,c("displ","year","cyl","cty","hwy")], label = TRUE)
To get something like this (obviously with the correlation figures rotated correctly):

ggparcoord define style for multiple plots
I would like to apply the same style of
ggparcoord
plotting to multiple plots without being repetitive. I've seen this done forggplot2
in general by defining axis styles before plotting and was wondering if something similar could be done forggparcoord
.For my specific situation, the styles span from appearing within the
ggparcoord
arguments to appearing outside of them, in the "theme" arguments. For example, in the following snippet I want to predefine everything that comes after the "groupColumn" argument, so that if I decide to change the style of all the plots I can do it in one place.library(GGally) p1 < ggparcoord(data = mtcars, columns = c(4:5), groupColumn = 1, scale="globalminmax", alphaLines = 0.2) + theme(legend.position ="none", axis.title.x=element_blank(), axis.title.y=element_blank()) + scale_x_discrete(expand = c(0,0)) p2 < ggparcoord(data = mtcars, columns = c(1:2), groupColumn = 2, scale="globalminmax", alphaLines = 0.2) + theme(legend.position ="none", axis.title.x=element_blank(), axis.title.y=element_blank()) + scale_x_discrete(expand = c(0,0))
I'm not sure how much of this question is ggparcoordspecific... Please modify the question as appropriate to make it generally useful.

ggparcoord axes adjustments: remove default labels, remove extra spacing
I'd like to remove the default "variable" and "value" labels on the axes of ggparcoord plots:
library(GGally) ggparcoord(data = mtcars, columns = c(4:5), groupColumn = 1, scale = "globalminmax", alphaLines = 0.2)
I'd also like to remove the default extra spaces on either end of the xaxis. How can I make these custom axis adjustments? Thanks!