vendredi 21 juin 2019

Replace elements in a vector using mapply if conditions are met

Trying to replace values in a vector if conditions are met using a quick apply function, but having a hard time with syntax.

 v1 <- c(-18,-18,-19,-20,-18,-18,-19)
 v2 <- c(34, 7,   8,   9,  7, 10, 30)

I want to compare elements in each vector and if v1 is less than -v2, replace it with the v2 value. I can easily identify those that need to be replaced:

 v1 < (-v2)
 [1] FALSE  TRUE  TRUE  TRUE  TRUE  TRUE FALSE

I tried to use this mapply function, but am getting the following error

 v1 <- mapply(function(x) if (x< (-v2)) (-v2) else x, v1) 

 Warning messages:
 1: In if (x < (-v2)) (-v2) else x :
   the condition has length > 1 and only the first element will be used
 2: In if (x < (-v2)) (-v2) else x :
   the condition has length > 1 and only the first element will be used

I think it's because I'm not specifically saying to compare elements in order, so it's only using the first element of one of the vectors, but I'm not quite sure how to do so. Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire