Javascript equivalent of Python’s zip function

2016 update: Here’s a snazzier Ecmascript 6 version: zip= rows=>rows[0].map((_,c)=>rows.map(row=>row[c])) Illustration equiv. to Python{zip(*args)}: > zip([[‘row0col0’, ‘row0col1’, ‘row0col2’], [‘row1col0’, ‘row1col1’, ‘row1col2’]]); [[“row0col0″,”row1col0”], [“row0col1″,”row1col1”], [“row0col2″,”row1col2”]] (and FizzyTea points out that ES6 has variadic argument syntax, so the following function definition will act like python, but see below for disclaimer… this will not be its own inverse … Read more

Transpose list of lists

Python 3: # short circuits at shortest nested list if table is jagged: list(map(list, zip(*l))) # discards no data if jagged and fills short nested lists with None list(map(list, itertools.zip_longest(*l, fillvalue=None))) Python 2: map(list, zip(*l)) [[1, 4, 7], [2, 5, 8], [3, 6, 9]] Explanation: There are two things we need to know to understand … Read more

Transpose / reshape dataframe without “timevar” from long to wide format

With the data.table package, this could easily be solved with the new rowid function: library(data.table) dcast(setDT(d1), Name ~ rowid(Name, prefix = “medication”), value.var = “MedName”) which gives: Name medication1 medication2 medication3 1 Name1 atenolol 25mg aspirin 81mg sildenafil 100mg 2 Name2 atenolol 50mg enalapril 20mg <NA> Another method (commonly used before version 1.9.7): dcast(setDT(d1)[, rn … Read more

R transpose and group by

This can be achieved using dcast() from the data.table package: library(data.table) dcast(DT, Client ~ rowid(Client, prefix = “Smoke “), value.var = “Smoke”) # Client Smoke 1 Smoke 2 Smoke 3 #1: 21 Y Y Y Data DT <- fread(“Client Smoke 0021 Y 0021 Y 0021 Y”)