Is there a way to access an index within a vector

后端 未结 3 2020
隐瞒了意图╮
隐瞒了意图╮ 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
    

提交回复
热议问题