如果/其他列表理解在R中

时间:2018-01-16 02:13:15

标签: r list-comprehension

我正在尝试使用List Comprehension计算R中的向量。我想要多个小于5或大于90乘10的元素,并将其他元素乘以0.1。目前我有if部分,但无法找到关于List Comprehension的else部分的足够信息。

x <- 1:100
10 * x [x < 5 | x > 90]

2 个答案:

答案 0 :(得分:0)

不需要ifelsekeeping in mind that ifelse is generally sort of slow):

newx = .1 * x + 9.9 * x * (x < 5 | x > 90)

或者更难读,但只需要一次比较:

newx = .1 * x + 9.9 * x * (abs(x - 5 - 85/2) > 85/2)

答案 1 :(得分:0)

使用我的包 listcompr 很容易阅读(但计算速度不是很快)的另一种解决方案:

library(listcompr)
gen.vector((if (x < 5 | x > 90) 10 else 0.1) * x, x = 1:100)
相关问题