Truncation of vector values based on another vector
Here is the general algorithm I wish to implement in R:
if (x[i]>y[i]) x[i] = y[i]
开发者_开发技巧
x
and y
are of course vectors. This problem looks like a loop is the solution.
A couple of possibilities. First with the ifelse function (since the if (){ } else{ } constuct does not work on vectors):
x <- ifelse( x > y, y, x)
Or with logical indexing:
x[ x>y ] <- y[ x>y ]
Both of these assume that x and y are the same length and are implicitly comparing and assigning elementwise so no need for an index
Good, DWin showed you already why you absolutely don't need a loop in R. But apparently you don't want to do what you asked, or your comment wouldn't make sense whatsoever.
If you want to choose which ones you want to change, you just add an extra logical vector to the solution of DWin, eg:
x <- 1:10
y <- 10:1
# say I want to change every second index
id <- seq.int(length(x))%%2
ifelse(x>y & id,y,x)
You can do what you want, as long as id :
- is as long as x and y
- contains 1/TRUE for can change and 0/FALSE for cannot change
The shortest answer is surely
x <- pmax(x,y)
精彩评论