首页 > 解决方案 > 如果满足条件,则使用 mapply 替换向量中的元素

问题描述

如果使用快速应用函数满足条件,则尝试替换向量中的值,但很难使用语法。

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

我想比较每个向量中的元素,如果 v1 小于 -v2,则将其替换为 v2 值。我可以很容易地识别出需要更换的那些:

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

我尝试使用此 mapply 函数,但出现以下错误

 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

我认为这是因为我并没有特别说要按顺序比较元素,所以它只使用其中一个向量的第一个元素,但我不太确定该怎么做。顺便说一句,我知道我可以用 for 循环来做到这一点,但我试图避免这种情况,因为数据集会非常大。提前致谢。

更新:我也试过这个,并得到一个新的错误

 v1 <- mapply(function(i) if(v1[i]< (-v2[i]) (-v2[i]) else v1[i], seq_along(v1))
 Error: unexpected 'else' in "v1 <- sapply(function(i) if(v1[i]< (-v2[i]) (-v2[i]) else"

标签: rif-statementvectorreplaceapply

解决方案


mapply您可以将函数应用于多个参数。在您的情况下,您的函数应该采用两个变量,例如:

v1 <- mapply(function(x,y) if (x < (-y)) (-y) else x, v1, v2)
v1
#[1] -18  -7  -8  -9  -7 -10 -19

正如Grada Gukovic所写,没有必要循环。在答案中,仅-缺少以下内容:

v1[v1 < (-v2)] <- -v2[v1 < (-v2)]
v1
#[1] -18  -7  -8  -9  -7 -10 -19

推荐阅读