简体   繁体   English

R:如何将向量中的元素放入新向量的特定位置

[英]R: how to get elements from a vector into specific positions of a new vector

I'm using R and I have the following vectors: 我正在使用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)

I want to combine even and odd so I can have a vector (let's say it will be named total) with the following elements 我想将偶数和奇数结合起来,这样我就可以得到一个带有以下元素的向量(假设它将被命名为total)

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

I've tried looping as: 我试过循环为:

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]

But for some reason this is not working. 但是由于某种原因,这是行不通的。 I'm getting this vector 我得到这个向量

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

does anyone no why my looping is not working for this case? 没有人不为什么我的循环不适用于这种情况吗?

of course, this is only a very simple example of what I have to do with a very large dataset. 当然,这只是一个非常简单的示例,说明了我如何处理非常大的数据集。

thanks! 谢谢!

I believe you problem is because you are adding items from odd(and even in the second loops) to the same position in the total using your code line: 我相信您的问题是因为您使用代码行将奇数(甚至在第二个循环中)项添加到总数中的相同位置:

total[i]<- odd[j]

try this instead; 试试这个

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 creates a sequence of values that I have used here to identify positions to insert the values from odd and even. seq创建了一个值序列,我在这里用它来标识从奇数和偶数插入值的位置。

Your loops are wrong. 您的循环是错误的。 As Scott mentioned you insert odd[j] into the same position in total for all values of j . 正如Scott所提到的,对于j所有值,您将odd[j]总共插入同一位置。 If you insist on using a for loop then if you do it like this you'll get what you want: 如果您坚持使用for循环,那么如果您这样做就可以得到所需的结果:

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

The methods provided by others don't use loops and are preferable. 其他人提供的方法不使用循环,因此更可取。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM