what is the best way to zip multiple lists in ImmutableJS - immutable.js

Assume i have a List of Lists. e.g:
const l : List<List<number>> = fromJS([[0,1,2,3],[4,5,6,7],[8,9,10,11]])
what is the best way (without using toJS()) to zip "l" so i'll get:
[[0,4,8],[1,5,9],[2,6,10],[3,7,11]]

I believe you want to use List#zip.
const l = Immutable.fromJS([
[0, 1, 2, 3],
[4, 5, 6, 7],
[8, 9, 10, 11]
]);
const zipped = l.get(0).zip(...l.rest());
console.log(zipped);
// [ [0,4,8], [1,5,9], [2,6,10], [3,7,11] ];
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/4.0.0-rc.9/immutable.js"></script>
Note that this returns a list of Arrays. It's easy enough to turn them into Lists though:
const zippedLists = zipped.map(List);
You might also be interested in List#zipAll if you're zipping lists of different sizes.

Related

Aurelia: Trying to make 2 HTML columns with single array

I'm having a problem figuring out how to make two equal columns (won't be exactly equal if the array length is odd) out of a single array.
So , and have them in two columns.
This isn't really a question specific to Aurelia, but I'm guessing the follow-up question would be.
won't be exactly equal if the array length is odd
That tells me you want to have this:
[1, 2, 3, 4, 5, 6]
And turn it into this:
[[1, 2], [3, 4], [5, 6]]
If you want to do this in a repeater, try this:
export class PairValueConverter {
fromView(input) {
return input.reduce((res, cur, i, arr) {
if (i % 2 === 0) res.push(arr.slice(i, i + 2));
return res;
}, []);
}
}
And then in your html:
<div repeat.for="item of items | pair">${item[0]} - ${item[1]}</div>
It's better if you put more effort in your question though, show what you've tried, etc. Someone might judge me for answering this :)

Plot colours in HTML differ from within RStudio after knit

I am trying to generate a shareable HTML document generated from an R Script in RStudio.
The script makes use of interactive plots generated from networkD3 and collapsibleTree packages. In the RStudio viewer, the colour scheme for these plots is highly visible; colours such as blue and red for the items.
However, when rendered in HTML, the colour scheme becomes a washed out grey: practically white on white background, which makes it too hard to see or use.
Can I specify plot colours in the RScript using a knitr passthrough, I don't know, something like:
#+ colourscheme(RdBu)
or do I need to generate some kind of CSS file to control plot colours? I am unclear and not very knowledgeable in this HTML area, and a little confused why the colours would change at all!
Thanks in advance for any help.
-- edit (example provided)
In response to the request below, I've generated a tiny example. However (!) when this is rendered, it retains the correct colour scheme. I'm unclear now what it is causing this; colours are linked to "gp" in my main diagram, and I have only 3 groups so should see 3 colours. I'm not able to provide a full example due to size (data limitations), so here's the outline:
nodes <- data.frame(Name = c('Alpha', 'Beta', 'Charlie'),
ID = c(0,1,2),
gp = c(1,1,2),
n = c(10,15,20))
links <- data.frame(x = c(0, 0, 0, 1, 1, 2, 2),
y = c(0, 1, 2, 1, 2, 0, 2),
n = c(8, 9, 8, 9, 8, 9, 8))
require(networkD3)
require(RColorBrewer)
forceNetwork(height = 200, width = 400,
Links = links, Nodes = nodes,
Source = "x", Target = "y", Value = "n", # From Links df
NodeID = "Name", Group = "gp", Nodesize = "n", # From Nodes df
arrows = T,
linkWidth = JS("function(d) { return Math.sqrt(d.value); }"),
#linkWidth = JS(" d.value"),
radiusCalculation = JS(" d.nodesize"),
charge = -10,
fontSize = 16,
colourScale = JS("d3.scaleOrdinal(d3.schemeCategory10);"),
opacity = 0.9,
bounded = T)
I'm guessing (?) that there's a certain set of conditions that triggers the colours to fail.
I'm pretty sure this happens because collapsibleTree is adding CSS that affects the elements created by forceNetwork. Can you try putting this minimal example in a .Rmd file and knit it to see if shows a similar problem...
---
output: html_document
---
```{r echo=FALSE}
nodes <- data.frame(NodeID = c("Alpha", "Beta", "Charlie"),
Group = c(1, 2, 3),
Nodesize = c(10, 15, 20))
links <- data.frame(Source = c(0, 0, 1, 2),
Target = c(1, 2, 2, 0),
Value = c(9, 8, 8, 9))
library(networkD3)
forceNetwork(Links = links, Nodes = nodes,
Source = "Source", Target = "Target", Value = "Value",
NodeID = "NodeID", Group = "Group", Nodesize = "Nodesize",
colourScale = JS("d3.scaleOrdinal(d3.schemeCategory10);"),
width = 100, height = 100)
```
```{r echo=FALSE}
library(collapsibleTree)
collapsibleTree(warpbreaks, c("wool", "tension", "breaks"),
width = 100, height = 100)
```
if so, try installing the dev version of collapsibleTree with devtools::install_github('AdeelK93/collapsibleTree') and then try it again and see if the problem goes away (and your other problem). They added namespaced css in this commit which hasn't made it into a CRAN release yet.

Selective rearrangement of columns in XMLListCollection not working

I am trying to selectively rearrange columns in my XMLListCollection but for some reasons it is not working.
As an example, say my array is - [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]. I am trying to shift 9th column to 2nd column. So my output shall be like this [1, 9, 2, 3, 4, 5, 6, 7, 8, 10].
I have tried the below code to achieve my result.
model.columns = new XMLListCollection(event.payload.Columns.Column);
// Selective re-arrangment
// Storing 9 col in backup variable
Var backUp:XMLListCollection = model.columns[9];
// Removing item from column 9
model.columns.removeItemAt(9);
// Inserting backup variable at desired index
model.columns.addItemAt(backUp,2)
// Code for rendering each column
for each( var col:XML in model.columns){
if(col.#visible == "Y"){
var dataGridColumn:FlexDataGridColumn = new FlexDataGridColumn();
dataGridColumn.headerText = col.#display_nm;
dataGridColumn.dataField = '#'+col.#variable;
view.adjustmentModuleColumns.addColumn( dataGridColumn);
view.adjustmentsDataGrid.reDraw();
}
}
For some reasons above code is not working as expected. Please suggest.

How to get only unique values of a 2d array

I need to get the following 2d array from:
[[Option 10, 2.0], [Option 10, 2.0], [Option 9, 1.0], [Option 7, 1.0]]
to
[[Option 10, 2.0], [Option 9, 1.0], [Option 7, 1.0]]
I found this post (Splitting a 2D array using some() , by date, avoiding duplicates. Just want 1 unique email, not row. Where am i wrong here?) that has a very efficient way of getting unique values, but I cannot figure out how to apply it to my situation.
Your use case is simpler than the one you refer to.
try this for example :
function myFunction() {
var source = [['Option 10', 2], ['Option 10', 2], ['Option 9', 1], ['Option 7', 1]];
var dest = [];
dest.push(source[0]);
for(var n = 1 ; n< source.length ; n++){
if(dest.join().indexOf(source[n].join()) == -1){dest.push(source[n])};
}
Logger.log(dest);
}
Because 'unique' is not always simple to describe, I often use a pattern which is is, in effect, a variation of Serge's correct answer using ES5 array map/filter functions.
An edited version:
function hash(arr) {
// in this case the hash method is the same as Serge's Array.join() method,
but could be customised to suit whatever condition you need to generate
bespoke comparators such as where `1 + 3` should match `2 + 2`, or where
particular columns in the array can be omitted
return arr.join();
}
function myFunction() {
var source = [['Option 10', 2], ['Option 10', 2], ['Option 9', 1], ['Option 7', 1]];
var hash = source.map(
function (row) {
return hash(row);
}
);
source = source.filter(
function (filterRow, i) {
return hash.slice(0, i).indexOf(hash(filterRow)) < 0;
}
);
Logger.log(source);
}
I only include this as there are times when your comparison may need to flex a little. In your example this isn't important which is why Serge's is correct, but I share to show a potential expansion food for thought for when unique needs to be 'tweaked'

Mathematica - CSV to Multidimensional Charts

I have a CSV file with 5 columns and about 2*104 rows that I need to visualise.
I've imported the file like so:
data = Import["res.csv", "CSV"];`
Now, I'm going to want to generate a lot of visuals from this - all 5 dimensions on a single plot as well as various cross sections.
My questions:
If I want to select, say columns 1, 4 and 5 from my data and feed them to ListPlot3D how would I do that?
And, values in columns can be grouped. So if I wanted to ListPlot3D colums 1, 2, 4 and 5, but I want to group columns 1 and 2 on the same axis, how would I tell Mathematica to do that?
Thanks.
I hate to disagree with a fellow poster especially after it has been accepted, but the Transpose is unnecessary. Almost everything you're asking for can be done within the context of Part:
ListPlot3D[ data[[All, {1, 4, 5}]] ]
Since matrices are stored row-wise within Mathematica, [[All, {1, 4, 5}]] can be read [[rows, columns]]. More specifically, All indicates here that you want all rows, but you can specify specific rows as well. Another construct that may be of interest is Span which is used to specify groups of indices, and if your CSV file contains a header row, you can strip it from your data using
ListPlot3D[ data[[ 2 ;; , {1, 4, 5}]] ]
As to your second requirement, to use both columns 1 and 2 as the x coordinate, then it is simply
ListPlot3D[ {data[[All, {2, 4, 5}]], data[[All, {1, 4, 5}]]} ]
and you change All to 2;; if you wish to strip off the header row.
If I understand you correctly that would be
ListPlot3D[Transpose[{data[[All, 1]], data[[All, 4]], data[[All, 5]]}]]
and for the multiple sets:
ListPlot3D[
{
Transpose[{data[[All, 1]], data[[All, 3]], data[[All, 4]]}],
Transpose[{data[[All, 2]], data[[All, 3]], data[[All, 5]]}]
}
]