R填充向量 [英] R populating a vector
本文介绍了R填充向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的矢量为零,长度为10.所以
I have a vector of zeros, say of length 10. So
v = rep(0,10)
我要基于v1中的一组索引和实际上具有顺序值的另一个矢量v2填充矢量的某些值.所以另一个向量v1的索引是
I want to populate some values of the vector, on the basis of a set of indexes in v1 and another vector v2 that actually has the values in sequence. So another vector v1 has the indexes say
v1 = c(1,2,3,7,8,9)
和
v2 = c(0.1,0.3,0.4,0.5,0.1,0.9)
最后我想要
v = c(0.1,0.3,0.4,0,0,0,0.5,0.1,0.9,0)
因此v1中的索引是从v2映射的,其余索引为0.我显然可以编写一个for循环,但是由于实际矩阵的长度,这在R中花费的时间太长.有任何简单的方法可以做到这一点吗?
So the indexes in v1 got mapped from v2 and the remaining ones were 0. I can obviously write a for loop but thats taking too long in R, owing to the length of the actual matrices. Any simple way to do this?
推荐答案
您可以通过以下方式进行分配:
You can assign it this way:
v[v1] = v2
例如:
> v = rep(0,10)
> v1 = c(1,2,3,7,8,9)
> v2 = c(0.1,0.3,0.4,0.5,0.1,0.9)
> v[v1] = v2
> v
[1] 0.1 0.3 0.4 0.0 0.0 0.0 0.5 0.1 0.9 0.0
这篇关于R填充向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文