Is there a way to access an index within a vector

后端 未结 3 2021
隐瞒了意图╮
隐瞒了意图╮ 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条回答
  • 2021-01-22 15:49

    It's not obvious from your question exactly what your problem is, but I'll guess it's one of the following:

    1. You are not quoting your strings properly.
    2. You are using variables that don't exist.
    3. You actually meant to create a list, not a concatenated vector

    Option 1: Use quote marks to indicate character vectors (strings)

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

    Option 2: You haven't defined your variables a-e and h

    > a <- 1
    > b <- 2
    > c <- 3
    > d <- 4
    > e <- 5
    > h <- 8
    > v1 <- c(a,b,c,d,e)
    > v1[3] = h
    > v1
    [1] 1 2 8 4 5
    

    Option 3: You meant to create and subset a list

    In this case you should use list instead of c. And remember that you index a list using double square brackets.

    a <- 1:5
    b <- 6:10
    c <- 11:15
    d <- 16:20
    e <- 21:25
    h <- 26:30
    v1 <- list(a,b,c,d,e)
    v1[[3]] <- h
    

    The list:

    v1
    [[1]]
    [1] 1 2 3 4 5
    
    [[2]]
    [1]  6  7  8  9 10
    
    [[3]]
    [1] 26 27 28 29 30
    
    [[4]]
    [1] 16 17 18 19 20
    
    [[5]]
    [1] 21 22 23 24 25
    

    Element 3 of the list:

    v1[[3]]
    [1] 26 27 28 29 30
    
    0 讨论(0)
  • 2021-01-22 15:53
    > v1 <- c(1,2,3)
    > v1[1] <- 5
    > v1
    [1] 5 2 3
    

    Um, that should work. I'm not sure that it's clear what your problem is. In your example, are a,b,c,d,e and h all defined? Or should you be using them as strings (ie "a", "b", etc)?

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题