Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List comprehension in R

Tags:

r

Is there a way to implement list comprehension in R?

Like python:

sum([x for x in range(1000) if x % 3== 0 or x % 5== 0]) 

same in Haskell:

sum [x| x<-[1..1000-1], x`mod` 3 ==0 || x `mod` 5 ==0 ] 

What's the practical way to apply this in R?

Nick

like image 293
Nick Avatar asked Apr 14 '13 11:04

Nick


People also ask

Can you do list comprehension in R?

Package provides Python-style list comprehensions for R. List comprehension expressions use usual loops ( for , while and repeat ) and usual if as list producers. Syntax is very similar to Python.

Is list comprehension faster than lambda?

Actually, list comprehension is much clearer and faster than filter+lambda, but you can use whichever you find easier. The first thing is the function call overhead: as soon as you use a Python function (whether created by def or lambda) it is likely that the filter will be slower than the list comprehension.

What is the difference between lambda and list comprehension?

The difference between Lambda and List Comprehension. List Comprehension is used to create lists, Lambda is function that can process like other functions and thus return values or lists.

Does list comprehension work on strings?

List comprehension works with string lists also. The following creates a new list of strings that contains 'a'.


2 Answers

Something like this?

l <- 1:1000 sum(l[l %% 3 == 0 | l %% 5 == 0]) 
like image 73
Ciarán Tobin Avatar answered Sep 24 '22 21:09

Ciarán Tobin


Yes, list comprehension is possible in R:

sum((1:1000)[(1:1000 %% 3) == 0 | (1:1000 %% 5) == 0]) 
like image 30
Nishanth Avatar answered Sep 21 '22 21:09

Nishanth