用向量替换向量的元素 [英] Replace elements of vector by vector

查看:46
本文介绍了用向量替换向量的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用整个第二个向量替换向量的几个元素.条件是,第一个向量的替换元素等于第三个向量.下面是一个例子:

I want to replace few elements of vector by whole second vector. Condition is, that replaced elements of first vector are equal to third vector. Here is an example:

 a <- 1:10
 b <- 5:7
 v <- rnorm(2, mean = 1, sd = 5)

我的输出应该是

 c(a[1:4], v, a[8:10])

我已经试过了

 replace(a, a == b, v)
 a[a == b] <- v

但取得了一些成功.有人可以帮忙吗?

but with a little success. Can anyone help?

推荐答案

这里有另一个选择:

a[a %in% b] <- v

由于在 OP 中描述的示例中,向量 ab 中有三个常用数字,而 v <- rnorm(2, mean =1, sd = 5)仅包含 2 个数字,向量 v 将被回收并发出警告.

Since in the example described in the OP there are three common numbers in the vectors a and b while v <- rnorm(2, mean = 1, sd = 5) contains only 2 numbers, the vector v will be recycled and a warning will be issued.

可以防止警告和回收,例如,通过将 v 定义为

The warning and recycling can be prevented, e.g., by defining v as

v <- rnorm(sum(a %in% b), mean = 1, sd = 5)

这篇关于用向量替换向量的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆