Is there a way to access an index within a vector

后端 未结 3 2024
隐瞒了意图╮
隐瞒了意图╮ 2021-01-22 15:35

i need to access an index (individual value) within a vector. I assumed it would be similar to:

v1 <- c(a,b,c,d,e)
v1[3] = h

But that doesn\

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-22 16:01

    If you have four vectors: v1, v2, v3, v4. then there are (at least) two ways to sequentially access them:

    The hard way (IMO):

    for ( i in 1:4 ) {print( get(paste("v", i, sep="") ) ) }
    

    The right way (also IMO):

    vlist <- list(v1, v2, v3, v4)
    for (v in vlist) print(v)
    

    In your revision it appears you constructed a third way:

    vlist <- list(v1, v2, v3, v4)
    for (v in 1:length(v) ) print( vlist[v] )
    

    ... which I would say was intermediate in right-ness between the first two constructions. The other thing you need to learn is that within a loop you need to DO SOMETHING to the values. Just putting mode(item) in the middle of the loop body will not produce any results. You need to assign it to a name or print it or ... something. Some of the commands you made are "doing something", but in the absence of a description of how they are failing to deliver what you expect and without the data, there not much that anyone can do to help further.

提交回复
热议问题