r - 如果满足条件,则使用 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"
解决方案
在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
推荐阅读
- arrays - 如何将 Twig 数组转换为 JavaScript 数组
- c++ - 通过指针偏移访问结构变量值
- python - 用部分路径名给出变量的完整路径?
- mysql - MySQL 和 PostgreSQL 行子查询运算符
- java - PreparedStatement isClosed() 挂起的任何原因?
- firebase - 将默认自定义声明添加到 firebase 令牌
- vba - 当我在 MsgBox 中单击 NO 或 CANCEL 时,我在 Excel VBA 中得到运行时 1004 错误,同时保存
- git - 如何知道创建实际分支的分支的名称?
- react-native - 在带有样式组件的本机反应中应用样式
- mongodb - Mongo在文档的嵌套数组中分组和分页