jf328 jf328 - 3 months ago 18
Python Question

List comprehension of 2+ variables in R

What's the best R equivalent of the Python 2-variable list comprehension

[datetime(y,m,15) for y in xrange(2000,2020) for m in [3,6,9,12]]


The result

[datetime.datetime(2000, 3, 15, 0, 0),
datetime.datetime(2000, 6, 15, 0, 0),
datetime.datetime(2000, 9, 15, 0, 0),
datetime.datetime(2000, 12, 15, 0, 0),
datetime.datetime(2001, 3, 15, 0, 0) ... ]

Answer

This will produce equivalent results in R

with(expand.grid(m=c(3,6,9,12), y=2000:2020), ISOdate(y,m,15))

We use expand.grid to get all combinations of year and month, and then we just use the vectorized ISOdate function to get the values.