List comprehension in R

前端 未结 7 1544
执笔经年
执笔经年 2020-12-24 11:48

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 H

7条回答
  •  半阙折子戏
    2020-12-24 11:56

    This list comprehension of the form:

    [item for item in list if test]
    

    is pretty straightforward with boolean indexing in R. But for more complex expressions, like implementing vector rescaling (I know this can be done with scales package too), in Python it's easy:

    x = [1, 3, 5, 7, 9, 11] # -> [0.0, 0.2, 0.4, 0.6, 0.8, 1.0]
    [(xi - min(x))/(max(x) - min(x)) for xi in x]
    

    But in R this is the best I could come up with. Would love to know if there's something better:

    sapply(x, function(xi, mn, mx) {(xi-mn)/(mx-mn)}, mn = min(x), mx = max(x))
    

提交回复
热议问题