0

I am trying to compute a vector in R using List Comprehension. I want to multiple elements that are smaller than 5 or larger than 90 by 10 and multiply the other elements by 0.1. Currently I have the if part but can't find sufficient information on the else part of a List Comprehension.

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

2 Answers2

1

No ifelse needed (keeping in mind that ifelse is generally sort of slow):

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

Or a bit harder to read but only need one comparison:

newx = .1 * x + 9.9 * x * (abs(x - 5 - 85/2) > 85/2)
MichaelChirico
  • 33,841
  • 14
  • 113
  • 198
0

Another solution which is very easy to read (but computationally not very fast) with my package listcompr:

library(listcompr)
gen.vector((if (x < 5 | x > 90) 10 else 0.1) * x, x = 1:100)
Patrick Roocks
  • 3,129
  • 3
  • 14
  • 28