2014-04-10 21 views
0

我使用R和我有以下的载体:R:如何从一个矢量元素到一个新的载体的特定位置

odd<- c(1,3,5,7,9,11,13,15,17,19) 
even<- c(2,4,6,8,10,12,14,16,18,20) 

我想奇数和偶数组合,所以我可以有一个矢量(假设它将被命名为总)包含以下元素

> total 
1,2,3,4,5,6,7,8,9,10...,20. 

我试过的循环:

total<- c(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0) #20 elements 

for (i in seq(from=1, to=20, by=2)) 
    for (j in seq(from=1, to=10, by=1)) 
    total[i]<- odd[j] 


for (i in seq(from=2, to=20, by=2)) 
     for (j in seq(from=1, to=10, by=1)) 
     total[i]<- even[j] 

但对于有些原因,这是行不通的。我得到这个载体

>total 
17 20 17 20 17 20 17 20 17 20 17 20 17 20 17 20 17 20 19 20 

没有人没有为什么我的循环不适用于这种情况?

当然,这只是一个非常简单的例子,我必须处理一个非常大的数据集。

谢谢!

+3

[Alternate,interweave或interlace two vectors]的可能副本(http://stackoverflow.com/questions/12044616/alternate-interweave-or-interlace-two-vectors)。你真的很想'c(rbind(奇怪,偶数))' – thelatemail

回答

0

我相信你的问题是因为您使用的代码行添加从奇(甚至在第二循环)项目在总同一位置:

total[i]<- odd[j] 

试试这个代替;

odd<- c(1,3,5,7,9,11,13,15,17,19) 
even<- c(2,4,6,8,10,12,14,16,18,20) 

elements = 20 
total<- rep(x=0, times=elements) #20 elements 

total[seq(from=1, to=length(total), by=2)] = odd 
total[seq(from=2, to=length(total), by=2)] = even 
total 

[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 

seq创建一个值序列,我在此使用它来标识插入奇数和偶数值的位置。

+1

感谢您的留言@Scott。我完全错过了使用序列总数[] =奇数或偶数的可能性,而不是在我的对象上循环两次! – mcarrol

0

您的循环错误。如Scott所说,您将odd[j]插入到j的所有值的总位置中。如果你坚持使用for循环然后如果你不喜欢这样,你会得到你想要的东西:

for (j in seq(from=1, to=10, by=1)) { 
    total[2*j-1]<- odd[j] 
    total[2*j] <- even[j] 
} 

他人提供不使用循环和是优选的方法。

+0

感谢您使用循环@Bhas的示例。是的,我做错了[j]。 – mcarrol

相关问题